diff --git a/include/QtCrypto/qca_basic.h b/include/QtCrypto/qca_basic.h index 3806c297..4e1b0da5 100644 --- a/include/QtCrypto/qca_basic.h +++ b/include/QtCrypto/qca_basic.h @@ -1,1083 +1,1140 @@ /* * qca_basic.h - Qt Cryptographic Architecture * Copyright (C) 2003-2007 Justin Karneges * Copyright (C) 2004-2007 Brad Hards * Copyright (C) 2013-2016 Ivan Romanov * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * */ /** \file qca_basic.h Header file for classes for cryptographic primitives (basic operations). \note You should not use this header directly from an application. You should just use \#include \ instead. */ #ifndef QCA_BASIC_H #define QCA_BASIC_H #include "qca_core.h" #include // Qt5 comes with QStringLiteral for wrapping string literals, which Qt4 does // not have. It is needed if the headers are built with QT_NO_CAST_FROM_ASCII. // Defining it here as QString::fromUtf8 for convenience. #ifndef QStringLiteral #define QStringLiteral(str) QString::fromUtf8(str) #endif namespace QCA { /** \defgroup UserAPI QCA user API This is the main set of QCA classes, intended for use in standard applications. */ /** \class Random qca_basic.h QtCrypto Source of random numbers. QCA provides a built in source of random numbers, which can be accessed through this class. You can also use an alternative random number source, by implementing another provider. The normal use of this class is expected to be through the static members - randomChar(), randomInt() and randomArray(). \ingroup UserAPI */ class QCA_EXPORT Random : public Algorithm { public: /** Standard Constructor \param provider the name of the provider library for the random number generation */ Random(const QString &provider = QString()); /** Copy constructor \param from the %Random object to copy from */ Random(const Random &from); ~Random(); /** Assignment operator \param from the %Random object to copy state from */ Random & operator=(const Random &from); /** Provide a random byte. This method isn't normally required - you should use the static randomChar() method instead. \sa randomChar */ uchar nextByte(); /** Provide a specified number of random bytes. This method isn't normally required - you should use the static randomArray() method instead. \param size the number of bytes to provide \sa randomArray */ SecureArray nextBytes(int size); /** Provide a random character (byte) This is the normal way of obtaining a single random char (ie. 8 bit byte), as shown below: \code myRandomChar = QCA::Random::randomChar(); \endcode If you need a number of bytes, perhaps randomArray() may be of use. */ static uchar randomChar(); /** Provide a random integer. This is the normal way of obtaining a single random integer, as shown below: \code myRandomInt = QCA::Random::randomInt(); \endcode */ static int randomInt(); /** Provide a specified number of random bytes. \code // build a 30 byte secure array. SecureArray arry = QCA::Random::randomArray(30); \endcode \param size the number of bytes to provide */ static SecureArray randomArray(int size); private: class Private; Private *d; }; /** \class Hash qca_basic.h QtCrypto General class for hashing algorithms. Hash is the class for the various hashing algorithms within %QCA. SHA256, SHA1 or RIPEMD160 are recommended for new applications, although MD2, MD4, MD5 or SHA0 may be applicable (for interoperability reasons) for some applications. To perform a hash, you create a Hash object, call update() with the data that needs to be hashed, and then call final(), which returns a QByteArray of the hash result. An example (using the SHA1 hash, with 1000 updates of a 1000 byte string) is shown below: \code if(!QCA::isSupported("sha1")) printf("SHA1 not supported!\n"); else { QByteArray fillerString; fillerString.fill('a', 1000); QCA::Hash shaHash("sha1"); for (int i=0; i<1000; i++) shaHash.update(fillerString); QByteArray hashResult = shaHash.final(); if ( "34aa973cd4c4daa4f61eeb2bdbad27316534016f" == QCA::arrayToHex(hashResult) ) { printf("big SHA1 is OK\n"); } else { printf("big SHA1 failed\n"); } } \endcode If you only have a simple hash requirement - a single string that is fully available in memory at one time - then you may be better off with one of the convenience methods. So, for example, instead of creating a QCA::Hash object, then doing a single update() and the final() call; you could simply call QCA::Hash("algoName").hash() with the data that you would otherwise have provided to the update() call. For more information on hashing algorithms, see \ref hashing. \ingroup UserAPI */ class QCA_EXPORT Hash : public Algorithm, public BufferedComputation { public: /** Constructor \param type label for the type of hash to be created (for example, "sha1" or "md2") \param provider the name of the provider plugin for the subclass (eg "qca-ossl") */ explicit Hash(const QString &type, const QString &provider = QString()); /** Copy constructor \param from the Hash object to copy from */ Hash(const Hash &from); ~Hash(); /** Assignment operator \param from the Hash object to copy state from */ Hash & operator=(const Hash &from); /** Returns a list of all of the hash types available \param provider the name of the provider to get a list from, if one provider is required. If not specified, available hash types from all providers will be returned. */ static QStringList supportedTypes(const QString &provider = QString()); /** Return the hash type */ QString type() const; /** Reset a hash, dumping all previous parts of the message. This method clears (or resets) the hash algorithm, effectively undoing any previous update() calls. You should use this call if you are re-using a Hash sub-class object to calculate additional hashes. */ virtual void clear(); /** Update a hash, adding more of the message contents to the digest. The whole message needs to be added using this method before you call final(). If you find yourself only calling update() once, you may be better off using a convenience method such as hash() or hashToString() instead. \param a the byte array to add to the hash */ virtual void update(const MemoryRegion &a); /** \overload \param a the QByteArray to add to the hash */ void update(const QByteArray &a); /** \overload This method is provided to assist with code that already exists, and is being ported to %QCA. You are better off passing a SecureArray (as shown above) if you are writing new code. \param data pointer to a char array \param len the length of the array. If not specified (or specified as a negative number), the length will be determined with strlen(), which may not be what you want if the array contains a null (0x00) character. */ void update(const char *data, int len = -1); /** \overload This allows you to read from a file or other I/O device. Note that the device must be already open for reading \param file an I/O device If you are trying to calculate the hash of a whole file (and it isn't already open), you might want to use code like this: \code QFile f( "file.dat" ); if ( f.open( QIODevice::ReadOnly ) ) { QCA::Hash hashObj("sha1"); hashObj.update( &f ); QByteArray output = hashObj.final().toByteArray(); } \endcode */ void update(QIODevice *file); /** Finalises input and returns the hash result After calling update() with the required data, the hash results are finalised and produced. Note that it is not possible to add further data (with update()) after calling final(), because of the way the hashing works - null bytes are inserted to pad the results up to a fixed size. If you want to reuse the Hash object, you should call clear() and start to update() again. */ virtual MemoryRegion final(); /** %Hash a byte array, returning it as another byte array This is a convenience method that returns the hash of a SecureArray. \code SecureArray sampleArray(3); sampleArray.fill('a'); SecureArray outputArray = QCA::Hash("md2")::hash(sampleArray); \endcode \param array the QByteArray to hash If you need more flexibility (e.g. you are constructing a large byte array object just to pass it to hash(), then consider creating an Hash object, and then calling update() and final(). */ MemoryRegion hash(const MemoryRegion &array); /** %Hash a byte array, returning it as a printable string This is a convenience method that returns the hash of a SecureArray as a hexadecimal representation encoded in a QString. \param array the QByteArray to hash If you need more flexibility, you can create a Hash object, call Hash::update() as required, then call Hash::final(), before using the static arrayToHex() method. */ QString hashToString(const MemoryRegion &array); private: class Private; Private *d; }; /** \page hashing Hashing Algorithms There are a range of hashing algorithms available in %QCA. Hashing algorithms are used with the Hash and MessageAuthenticationCode classes. The MD2 algorithm takes an arbitrary data stream, known as the message and outputs a condensed 128 bit (16 byte) representation of that data stream, known as the message digest. This algorithm is considered slightly more secure than MD5, but is more expensive to compute. Unless backward compatibility or interoperability are considerations, you are better off using the SHA1 or RIPEMD160 hashing algorithms. For more information on %MD2, see B. Kalinski RFC1319 "The %MD2 Message-Digest Algorithm". The label for MD2 is "md2". The MD4 algorithm takes an arbitrary data stream, known as the message and outputs a condensed 128 bit (16 byte) representation of that data stream, known as the message digest. MD4 is not considered to be secure, based on known attacks. It should only be used for applications where collision attacks are not a consideration (for example, as used in the rsync algorithm for fingerprinting blocks of data). If a secure hash is required, you are better off using the SHA1 or RIPEMD160 hashing algorithms. MD2 and MD5 are both stronger 128 bit hashes. For more information on MD4, see R. Rivest RFC1320 "The %MD4 Message-Digest Algorithm". The label for MD4 is "md4". The MD5 takes an arbitrary data stream, known as the message and outputs a condensed 128 bit (16 byte) representation of that data stream, known as the message digest. MD5 is not considered to be secure, based on known attacks. It should only be used for applications where collision attacks are not a consideration. If a secure hash is required, you are better off using the SHA1 or RIPEMD160 hashing algorithms. For more information on MD5, see R. Rivest RFC1321 "The %MD5 Message-Digest Algorithm". The label for MD5 is "md5". The RIPEMD160 algorithm takes an arbitrary data stream, known as the message (up to \f$2^{64}\f$ bits in length) and outputs a condensed 160 bit (20 byte) representation of that data stream, known as the message digest. The RIPEMD160 algorithm is considered secure in that it is considered computationally infeasible to find the message that produced the message digest. The label for RIPEMD160 is "ripemd160". The SHA-0 algorithm is a 160 bit hashing function, no longer recommended for new applications because of known (partial) attacks against it. The label for SHA-0 is "sha0". The SHA-1 algorithm takes an arbitrary data stream, known as the message (up to \f$2^{64}\f$ bits in length) and outputs a condensed 160 bit (20 byte) representation of that data stream, known as the message digest. SHA-1 is considered secure in that it is considered computationally infeasible to find the message that produced the message digest. For more information on the SHA-1 algorithm,, see Federal Information Processing Standard Publication 180-2 "Specifications for the Secure %Hash Standard", available from http://csrc.nist.gov/publications/. The label for SHA-1 is "sha1". The SHA-224 algorithm takes an arbitrary data stream, known as the message (up to \f$2^{64}\f$ bits in length) and outputs a condensed 224 bit (28 byte) representation of that data stream, known as the message digest. SHA-224 is a "cut down" version of SHA-256, and you may be better off using SHA-256 in new designs. The SHA-224 algorithm is considered secure in that it is considered computationally infeasible to find the message that produced the message digest. For more information on SHA-224, see Federal Information Processing Standard Publication 180-2 "Specifications for the Secure %Hash Standard", with change notice 1, available from http://csrc.nist.gov/publications/. The label for SHA-224 is "sha224". The SHA-256 algorithm takes an arbitrary data stream, known as the message (up to \f$2^{64}\f$ bits in length) and outputs a condensed 256 bit (32 byte) representation of that data stream, known as the message digest. The SHA-256 algorithm is considered secure in that it is considered computationally infeasible to find the message that produced the message digest. For more information on SHA-256, see Federal Information Processing Standard Publication 180-2 "Specifications for the Secure %Hash Standard", available from http://csrc.nist.gov/publications/. The label for SHA-256 is "sha256". The SHA-384 algorithm takes an arbitrary data stream, known as the message (up to \f$2^{128}\f$ bits in length) and outputs a condensed 384 bit (48 byte) representation of that data stream, known as the message digest. The SHA-384 algorithm is a "cut down" version of SHA-512, and you may be better off using SHA-512 in new designs. The SHA-384 algorithm is considered secure in that it is considered computationally infeasible to find the message that produced the message digest. For more information on SHA-384, see Federal Information Processing Standard Publication 180-2 "Specifications for the Secure %Hash Standard", available from http://csrc.nist.gov/publications/. The label for SHA-384 is "sha384". The SHA-512 algorithm takes an arbitrary data stream, known as the message (up to \f$2^{128}\f$ bits in length) and outputs a condensed 512 bit (64 byte) representation of that data stream, known as the message digest. The SHA-512 algorithm is considered secure in that it is considered computationally infeasible to find the message that produced the message digest. For more information on SHA-512, see Federal Information Processing Standard Publication 180-2 "Specifications for the Secure %Hash Standard", available from http://csrc.nist.gov/publications/. The label for SHA-512 is "sha512". The Whirlpool algorithm takes an arbitrary data stream, known as the message (up to \f$2^{256}\f$ bits in length) and outputs a condensed 512 bit (64 byte) representation of that data stream, known as the message digest. The Whirlpool algorithm is considered secure in that it is considered computationally infeasible to find the message that produced the message digest. For more information on Whirlpool, see http://paginas.terra.com.br/informatica/paulobarreto/WhirlpoolPage.html or ISO/IEC 10118-3:2004. The label for Whirlpool is "whirlpool". */ /** \page paddingDescription Padding For those Cipher sub-classes that are block based, there are modes that require a full block on encryption and decryption - %Cipher Block Chaining mode and Electronic Code Book modes are good examples. Since real world messages are not always a convenient multiple of a block size, we have to adding padding. There are a number of padding modes that %QCA supports, including not doing any padding at all. If you are not going to use padding, then you can pass QCA::Cipher::NoPadding as the pad argument to the Cipher sub-class, however it is then your responsibility to pass in appropriate data for the mode that you are using. The most common padding scheme is known as PKCS#7 (also PKCS#1), and it specifies that the pad bytes are all equal to the length of the padding ( for example, if you need three pad bytes to complete the block, then the padding is 0x03 0x03 0x03 ). PKCS#5 padding is a subset of PKCS#7 padding for 8 byte block sizes. For explanation, see http://crypto.stackexchange.com/questions/9043/what-is-the-difference-between-pkcs5-padding-and-pkcs7-padding/9044#9044. On encryption, for algorithm / mode combinations that require padding, you will get a block of ciphertext when the input plain text block is complete. When you call final(), you will get out the ciphertext that corresponds to the last part of the plain text, plus any padding. If you had provided plaintext that matched up with a block size, then the cipher text block is generated from pure padding - you always get at least some padding, to ensure that the padding can be safely removed on decryption. On decryption, for algorithm / mode combinations that use padding, you will get back a block of plaintext when the input ciphertext block is complete. When you call final(), you will get a block that has been stripped of ciphertext. */ /** \class Cipher qca_basic.h QtCrypto General class for cipher (encryption / decryption) algorithms. Cipher is the class for the various algorithms that perform low level encryption and decryption within %QCA. AES128, AES192 and AES256 are recommended for new applications. Standard names for ciphers are: - Blowfish - "blowfish" - TripleDES - "tripledes" - DES - "des" - AES128 - "aes128" - AES192 - "aes192" - AES256 - "aes256" - CAST5 (CAST-128) - "cast5" When checking for the availability of a particular kind of cipher operation (e.g. AES128 in CBC mode with PKCS7 padding), you append the mode and padding type (in that example "aes128-cbc-pkcs7"). CFB and OFB modes don't use padding, so they are always just the cipher name followed by the mode (e.g. "blowfish-cfb" or "aes192-ofb"). If you are not using padding with CBC mode (i.e. you are ensuring block size operations yourself), just use the cipher name followed by "-cbc" (e.g. "blowfish-cbc" or "aes256-cbc"). \ingroup UserAPI */ class QCA_EXPORT Cipher : public Algorithm, public Filter { public: /** Mode settings for cipher algorithms. \note ECB is almost never what you want, unless you are trying to implement a %Cipher variation that is not supported by %QCA. */ enum Mode { CBC, ///< operate in %Cipher Block Chaining mode CFB, ///< operate in %Cipher FeedBack mode ECB, ///< operate in Electronic Code Book mode OFB, ///< operate in Output FeedBack Mode CTR, ///< operate in CounTer Mode GCM, ///< operate in Galois Counter Mode CCM ///< operate in Counter with CBC-MAC }; /** Padding variations for cipher algorithms. See the \ref paddingDescription description for more details on padding schemes. */ enum Padding { DefaultPadding, ///< Default for cipher-mode NoPadding, ///< Do not use padding PKCS7 ///< Pad using the scheme in PKCS#7 }; /** Standard constructor \param type the name of the cipher specialisation to use (e.g. "aes128") \param mode the operating Mode to use (e.g. QCA::Cipher::CBC) \param pad the type of Padding to use \param dir the Direction that this Cipher should use (Encode for encryption, Decode for decryption) \param key the SymmetricKey array that is the key \param iv the InitializationVector to use (not used for ECB mode) \param provider the name of the Provider to use \note Padding only applies to CBC and ECB modes. CFB and OFB ciphertext is always the length of the plaintext. */ Cipher(const QString &type, Mode mode, Padding pad = DefaultPadding, Direction dir = Encode, const SymmetricKey &key = SymmetricKey(), const InitializationVector &iv = InitializationVector(), const QString &provider = QString()); /** Standard constructor \param type the name of the cipher specialisation to use (e.g. "aes128") \param mode the operating Mode to use (e.g. QCA::Cipher::CBC) \param pad the type of Padding to use \param dir the Direction that this Cipher should use (Encode for encryption, Decode for decryption) \param key the SymmetricKey array that is the key \param iv the InitializationVector to use (not used for ECB mode) \param tag the AuthTag to use (only for GCM and CCM modes) \param provider the name of the Provider to use \note Padding only applies to CBC and ECB modes. CFB and OFB ciphertext is always the length of the plaintext. */ Cipher(const QString &type, Mode mode, Padding pad, Direction dir, const SymmetricKey &key, const InitializationVector &iv, const AuthTag &tag, const QString &provider = QString()); /** Standard copy constructor \param from the Cipher to copy state from */ Cipher(const Cipher &from); ~Cipher(); /** Assignment operator \param from the Cipher to copy state from */ Cipher & operator=(const Cipher &from); /** Returns a list of all of the cipher types available \param provider the name of the provider to get a list from, if one provider is required. If not specified, available cipher types from all providers will be returned. */ static QStringList supportedTypes(const QString &provider = QString()); /** Return the cipher type */ QString type() const; /** Return the cipher mode */ Mode mode() const; /** Return the cipher padding type */ Padding padding() const; /** Return the cipher direction */ Direction direction() const; /** Return acceptable key lengths */ KeyLength keyLength() const; /** Test if a key length is valid for the cipher algorithm \param n the key length in bytes \return true if the key would be valid for the current algorithm */ bool validKeyLength(int n) const; /** return the block size for the cipher object */ int blockSize() const; /** return the authentication tag for the cipher object */ AuthTag tag() const; /** reset the cipher object, to allow re-use */ virtual void clear(); /** pass in a byte array of data, which will be encrypted or decrypted (according to the Direction that was set in the constructor or in setup() ) and returned. \param a the array of data to encrypt / decrypt */ virtual MemoryRegion update(const MemoryRegion &a); /** complete the block of data, padding as required, and returning the completed block */ virtual MemoryRegion final(); /** Test if an update() or final() call succeeded. \return true if the previous call succeeded */ virtual bool ok() const; /** Reset / reconfigure the Cipher You can use this to re-use an existing Cipher, rather than creating a new object with a slightly different configuration. \param dir the Direction that this Cipher should use (Encode for encryption, Decode for decryption) \param key the SymmetricKey array that is the key \param iv the InitializationVector to use (not used for ECB Mode) \note You should not leave iv empty for any Mode except ECB. */ void setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv = InitializationVector()); /** Reset / reconfigure the Cipher You can use this to re-use an existing Cipher, rather than creating a new object with a slightly different configuration. \param dir the Direction that this Cipher should use (Encode for encryption, Decode for decryption) \param key the SymmetricKey array that is the key \param iv the InitializationVector to use (not used for ECB Mode) \param tag the AuthTag to use (only for GCM and CCM modes) \note You should not leave iv empty for any Mode except ECB. */ void setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv, const AuthTag &tag); /** Construct a Cipher type string \param cipherType the name of the algorithm (eg AES128, DES) \param modeType the mode to operate the cipher in (eg QCA::CBC, QCA::CFB) \param paddingType the padding required (eg QCA::NoPadding, QCA::PCKS7) */ static QString withAlgorithms(const QString &cipherType, Mode modeType, Padding paddingType); private: class Private; Private *d; }; /** \class MessageAuthenticationCode qca_basic.h QtCrypto General class for message authentication code (MAC) algorithms. MessageAuthenticationCode is a class for accessing the various message authentication code algorithms within %QCA. HMAC using SHA1 ("hmac(sha1)") or HMAC using SHA256 ("hmac(sha256)") is recommended for new applications. Note that if your application is potentially susceptable to "replay attacks" where the message is sent more than once, you should include a counter in the message that is covered by the MAC, and check that the counter is always incremented every time you receive a message and MAC. For more information on HMAC, see H. Krawczyk et al. RFC2104 "HMAC: Keyed-Hashing for Message Authentication" \ingroup UserAPI */ class QCA_EXPORT MessageAuthenticationCode : public Algorithm, public BufferedComputation { public: /** Standard constructor \param type the name of the MAC (and algorithm, if applicable) to use \param key the shared key \param provider the provider to use, if a particular provider is required */ MessageAuthenticationCode(const QString &type, const SymmetricKey &key, const QString &provider = QString()); /** Standard copy constructor Copies the state (including key) from one MessageAuthenticationCode to another \param from the MessageAuthenticationCode to copy state from */ MessageAuthenticationCode(const MessageAuthenticationCode &from); ~MessageAuthenticationCode(); /** Assignment operator. Copies the state (including key) from one MessageAuthenticationCode to another \param from the MessageAuthenticationCode to assign from. */ MessageAuthenticationCode & operator=(const MessageAuthenticationCode &from); /** Returns a list of all of the message authentication code types available \param provider the name of the provider to get a list from, if one provider is required. If not specified, available message authentication codes types from all providers will be returned. */ static QStringList supportedTypes(const QString &provider = QString()); /** Return the MAC type */ QString type() const; /** Return acceptable key lengths */ KeyLength keyLength() const; /** Test if a key length is valid for the MAC algorithm \param n the key length in bytes \return true if the key would be valid for the current algorithm */ bool validKeyLength(int n) const; /** Reset a MessageAuthenticationCode, dumping all previous parts of the message. This method clears (or resets) the algorithm, effectively undoing any previous update() calls. You should use this call if you are re-using a %MessageAuthenticationCode sub-class object to calculate additional MACs. Note that if the key doesn't need to be changed, you don't need to call setup() again, since the key can just be reused. */ virtual void clear(); /** Update the MAC, adding more of the message contents to the digest. The whole message needs to be added using this method before you call final(). \param array the message contents */ virtual void update(const MemoryRegion &array); /** Finalises input and returns the MAC result After calling update() with the required data, the hash results are finalised and produced. Note that it is not possible to add further data (with update()) after calling final(). If you want to reuse the %MessageAuthenticationCode object, you should call clear() and start to update() again. */ virtual MemoryRegion final(); /** Initialise the MAC algorithm \param key the key to use for the algorithm */ void setup(const SymmetricKey &key); private: class Private; Private *d; }; /** \class KeyDerivationFunction qca_basic.h QtCrypto General superclass for key derivation algorithms. %KeyDerivationFunction is a superclass for the various key derivation function algorithms within %QCA. You should not need to use it directly unless you are adding another key derivation capability to %QCA - you should be using a sub-class. PBKDF2 using SHA1 is recommended for new applications. \ingroup UserAPI */ class QCA_EXPORT KeyDerivationFunction : public Algorithm { public: /** Standard copy constructor \param from the KeyDerivationFunction to copy from */ KeyDerivationFunction(const KeyDerivationFunction &from); ~KeyDerivationFunction(); /** Assignment operator Copies the state (including key) from one KeyDerivationFunction to another \param from the KeyDerivationFunction to assign from */ KeyDerivationFunction & operator=(const KeyDerivationFunction &from); /** Generate the key from a specified secret and salt value \note key length is ignored for some functions \param secret the secret (password or passphrase) \param salt the salt to use \param keyLength the length of key to return \param iterationCount the number of iterations to perform \return the derived key */ SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, unsigned int iterationCount); /** Generate the key from a specified secret and salt value \note key length is ignored for some functions \param secret the secret (password or passphrase) \param salt the salt to use \param keyLength the length of key to return \param msecInterval the maximum time to compute the key, in milliseconds \param iterationCount a pointer to store the number of iteration done for the specified time \return the derived key */ SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, int msecInterval, unsigned int *iterationCount); /** Construct the name of the algorithm You can use this to build a standard name string. You probably only need this method if you are creating a new subclass. \param kdfType the type of key derivation function \param algType the name of the algorithm to use with the key derivation function \return the name of the KDF/algorithm pair */ static QString withAlgorithm(const QString &kdfType, const QString &algType); protected: /** Special constructor for subclass initialisation \param type the algorithm to create \param provider the name of the provider to create the key derivation function in. */ KeyDerivationFunction(const QString &type, const QString &provider); private: class Private; Private *d; }; /** \class PBKDF1 qca_basic.h QtCrypto Password based key derivation function version 1 This class implements Password Based Key Derivation Function version 1, as specified in RFC2898, and also in PKCS#5. \ingroup UserAPI */ class QCA_EXPORT PBKDF1 : public KeyDerivationFunction { public: /** Standard constructor \param algorithm the name of the hashing algorithm to use \param provider the name of the provider to use, if available */ explicit PBKDF1(const QString &algorithm = QStringLiteral("sha1"), const QString &provider = QString()) : KeyDerivationFunction(withAlgorithm(QStringLiteral("pbkdf1"), algorithm), provider) {} }; /** \class PBKDF2 qca_basic.h QtCrypto Password based key derivation function version 2 This class implements Password Based Key Derivation Function version 2, as specified in RFC2898, and also in PKCS#5. \ingroup UserAPI */ class QCA_EXPORT PBKDF2 : public KeyDerivationFunction { public: /** Standard constructor \param algorithm the name of the hashing algorithm to use \param provider the name of the provider to use, if available */ explicit PBKDF2(const QString &algorithm = QStringLiteral("sha1"), const QString &provider = QString()) : KeyDerivationFunction(withAlgorithm(QStringLiteral("pbkdf2"), algorithm), provider) {} }; +/** + \class HKDF qca_basic.h QtCrypto + \since 2.3 + + HMAC-based extract-and-expand key derivation function + + This class implements HMAC-based Extract-and-Expand Key Derivation Function, + as specified in RFC5869. + + \ingroup UserAPI +*/ +class QCA_EXPORT HKDF : public Algorithm +{ +public: + /** + Standard constructor + + \param algorithm the name of the hashing algorithm to use + \param provider the name of the provider to use, if available + */ + explicit HKDF(const QString &algorithm = QStringLiteral("sha256"), const QString &provider = QString()); + + /** + Standard copy constructor + + \param from the KeyDerivationFunction to copy from + */ + HKDF(const HKDF &from); + + ~HKDF(); + + /** + Assignment operator + + Copies the state (including key) from one HKDF + to another + + \param from the HKDF to assign from + */ + HKDF & operator=(const HKDF &from); + + /** + Generate the key from a specified secret, salt value, and an additional info + + \note key length is ignored for some functions + + \param secret the secret (password or passphrase) + \param salt the salt to use + \param info the info to use + \param keyLength the length of key to return + + \return the derived key + */ + SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, + const InitializationVector &info, unsigned int keyLength); +}; + } #endif diff --git a/include/QtCrypto/qcaprovider.h b/include/QtCrypto/qcaprovider.h index d4b54f98..92f20547 100644 --- a/include/QtCrypto/qcaprovider.h +++ b/include/QtCrypto/qcaprovider.h @@ -1,3008 +1,3042 @@ /* * qcaprovider.h - QCA Plugin API * Copyright (C) 2003-2007 Justin Karneges * Copyright (C) 2004,2005 Brad Hards * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * */ /** \file qcaprovider.h Header file for provider implementation classes (plugins) \note You should not use this header directly from an application. You should just use \#include \ instead. */ #ifndef QCAPROVIDER_H #define QCAPROVIDER_H #include "qca_core.h" #include "qca_basic.h" #include "qca_publickey.h" #include "qca_cert.h" #include "qca_keystore.h" #include "qca_securelayer.h" #include "qca_securemessage.h" #include #ifndef DOXYGEN_NO_PROVIDER_API /** \defgroup ProviderAPI QCA provider API This group of classes is not normally needed by application writers, but can be used to extend QCA if required */ /** \class QCAPlugin qcaprovider.h QtCrypto Provider plugin base class QCA loads cryptographic provider plugins with QPluginLoader. The QObject obtained when loading the plugin must implement the QCAPlugin interface. This is done by inheriting QCAPlugin, and including Q_INTERFACES(QCAPlugin) in your class declaration. For example: \code class MyPlugin : public QObject, public QCAPlugin { Q_OBJECT Q_INTERFACES(QCAPlugin) public: virtual Provider *createProvider() { ... } }; \endcode There is only one function to reimplement, called createProvider(). This function should return a newly allocated Provider instance. \ingroup ProviderAPI */ class QCA_EXPORT QCAPlugin { public: /** Destructs the object */ virtual ~QCAPlugin() {} /** Returns a newly allocated Provider instance. */ virtual QCA::Provider *createProvider() = 0; }; Q_DECLARE_INTERFACE(QCAPlugin, "com.affinix.qca.Plugin/1.0") namespace QCA { /** \class InfoContext qcaprovider.h QtCrypto Extended provider information \note This class is part of the provider plugin interface and should not be used directly by applications. \ingroup ProviderAPI */ class QCA_EXPORT InfoContext : public BasicContext { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context */ InfoContext(Provider *p) : BasicContext(p, QStringLiteral("info") ) {} /** The hash algorithms supported by the provider */ virtual QStringList supportedHashTypes() const; /** The cipher algorithms supported by the provider */ virtual QStringList supportedCipherTypes() const; /** The mac algorithms supported by the provider */ virtual QStringList supportedMACTypes() const; }; /** \class RandomContext qcaprovider.h QtCrypto Random provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want Random instead. \ingroup ProviderAPI */ class QCA_EXPORT RandomContext : public BasicContext { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context */ RandomContext(Provider *p) : BasicContext(p, QStringLiteral("random")) {} /** Return an array of random bytes \param size the number of random bytes to return */ virtual SecureArray nextBytes(int size) = 0; }; /** \class HashContext qcaprovider.h QtCrypto Hash provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want Hash instead. \ingroup ProviderAPI */ class QCA_EXPORT HashContext : public BasicContext { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context \param type the name of the type of hash provided by this context */ HashContext(Provider *p, const QString &type) : BasicContext(p, type) {} /** Reset the object to its initial state */ virtual void clear() = 0; /** Process a chunk of data \param a the input data to process */ virtual void update(const MemoryRegion &a) = 0; /** Return the computed hash */ virtual MemoryRegion final() = 0; }; /** \class CipherContext qcaprovider.h QtCrypto Cipher provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want Cipher instead. \ingroup ProviderAPI */ class QCA_EXPORT CipherContext : public BasicContext { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context \param type the name of the type of cipher provided by this context \note type includes the name of the cipher (e.g. "aes256"), the operating mode (e.g. "cbc" or "ofb") and the padding type (e.g. "pkcs7") if any. */ CipherContext(Provider *p, const QString &type) : BasicContext(p, type) {} /** Set up the object for encrypt/decrypt \param dir the direction for the cipher (encryption/decryption) \param key the symmetric key to use for the cipher \param iv the initialization vector to use for the cipher (not used in ECB mode) \param tag the AuthTag to use (only for GCM and CCM modes) */ virtual void setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv, const AuthTag &tag) = 0; /** Returns the KeyLength for this cipher */ virtual KeyLength keyLength() const = 0; /** Returns the block size for this cipher */ virtual int blockSize() const = 0; /** Returns the authentication tag for this cipher */ virtual AuthTag tag() const = 0; /** Process a chunk of data. Returns true if successful. \param in the input data to process \param out pointer to an array that should store the result */ virtual bool update(const SecureArray &in, SecureArray *out) = 0; /** Finish the cipher processing. Returns true if successful. \param out pointer to an array that should store the result */ virtual bool final(SecureArray *out) = 0; }; /** \class MACContext qcaprovider.h QtCrypto Message authentication code provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want MessageAuthenticationCode instead. \ingroup ProviderAPI */ class QCA_EXPORT MACContext : public BasicContext { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context \param type the name of the type of MAC algorithm provided by this context */ MACContext(Provider *p, const QString &type) : BasicContext(p, type) {} /** Set up the object for hashing \param key the key to use with the MAC. */ virtual void setup(const SymmetricKey &key) = 0; /** Returns the KeyLength for this MAC algorithm */ virtual KeyLength keyLength() const = 0; /** Process a chunk of data \param in the input data to process */ virtual void update(const MemoryRegion &in) = 0; /** Compute the result after processing all data \param out pointer to an array that should store the result */ virtual void final(MemoryRegion *out) = 0; protected: /** Returns a KeyLength that supports any length */ KeyLength anyKeyLength() const { // this is used instead of a default implementation to make sure that // provider authors think about it, at least a bit. // See Meyers, Effective C++, Effective C++ (2nd Ed), Item 36 return KeyLength( 0, INT_MAX, 1 ); } }; /** \class KDFContext qcaprovider.h QtCrypto Key derivation function provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want KeyDerivationFunction instead. \ingroup ProviderAPI */ class QCA_EXPORT KDFContext : public BasicContext { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context \param type the name of the KDF provided by this context (including algorithm) */ KDFContext(Provider *p, const QString &type) : BasicContext(p, type) {} /** Create a key and return it \param secret the secret part (typically password) \param salt the salt / initialization vector \param keyLength the length of the key to be produced \param iterationCount the number of iterations of the derivation algorith, */ virtual SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, unsigned int iterationCount) = 0; /** Create a key and return it \param secret the secret part (typically password) \param salt the salt / initialization vector \param keyLength the length of the key to be produced \param msecInterval the maximum time to compute the key, in milliseconds \param iterationCount a pointer to store the number of iterations of the derivation algorithm, */ virtual SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, int msecInterval, unsigned int *iterationCount) = 0; }; +/** + \class HKDFContext qcaprovider.h QtCrypto + + HKDF provider + + \note This class is part of the provider plugin interface and should not + be used directly by applications. You probably want HKDF instead. + + \ingroup ProviderAPI +*/ +class QCA_EXPORT HKDFContext : public BasicContext +{ + Q_OBJECT +public: + /** + Standard constructor + + \param p the provider associated with this context + \param type the name of the HKDF provided by this context (including algorithm) + */ + HKDFContext(Provider *p, const QString &type) : BasicContext(p, type) {} + + /** + Create a key and return it + + \param secret the secret part (typically password) + \param salt the salt / initialization vector + \param info the info / initialization vector + \param keyLength the length of the key to be produced + */ + virtual SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, + const InitializationVector &info, unsigned int keyLength) = 0; +}; + /** \class DLGroupContext qcaprovider.h QtCrypto Discrete logarithm provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want DLGroup instead. \ingroup ProviderAPI */ class QCA_EXPORT DLGroupContext : public Provider::Context { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context */ DLGroupContext(Provider *p) : Provider::Context(p, QStringLiteral("dlgroup")) {} /** The DLGroupSets supported by this object */ virtual QList supportedGroupSets() const = 0; /** Returns true if there is a result to obtain */ virtual bool isNull() const = 0; /** Attempt to create P, Q, and G values from the specified group set If \a block is true, then this function blocks until completion. Otherwise, this function returns immediately and finished() is emitted when the operation completes. If an error occurs during generation, then the operation will complete and isNull() will return true. \param set the group set to generate the key from \param block whether to block (true) or not (false) */ virtual void fetchGroup(DLGroupSet set, bool block) = 0; /** Obtain the result of the operation. Ensure isNull() returns false before calling this function. \param p the P value \param q the Q value \param g the G value */ virtual void getResult(BigInteger *p, BigInteger *q, BigInteger *g) const = 0; Q_SIGNALS: /** Emitted when the fetchGroup() operation completes in non-blocking mode. */ void finished(); }; /** \class PKeyBase qcaprovider.h QtCrypto Public key implementation provider base \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want PKey, PublicKey, or PrivateKey instead. \ingroup ProviderAPI */ class QCA_EXPORT PKeyBase : public BasicContext { Q_OBJECT public: /** Standard constructor \param p the Provider associated with this context \param type type of key provided by this context */ PKeyBase(Provider *p, const QString &type); /** Returns true if this object is not valid. This is the default state, and the object may also become this state if a conversion or generation function fails. */ virtual bool isNull() const = 0; /** Returns the type of public key */ virtual PKey::Type type() const = 0; /** Returns true if this is a private key, otherwise false */ virtual bool isPrivate() const = 0; /** Returns true if the components of this key are accessible and whether it can be serialized into an output format. Private keys from a smart card device will often not be exportable. */ virtual bool canExport() const = 0; /** If the key is a private key, this function will convert it into a public key (all private key data includes the public data as well, which is why this is possible). If the key is already a public key, then this function has no effect. */ virtual void convertToPublic() = 0; /** Returns the number of bits in the key */ virtual int bits() const = 0; /** Returns the maximum number of bytes that can be encrypted by this key \param alg the algorithm to be used for encryption */ virtual int maximumEncryptSize(EncryptionAlgorithm alg) const; /** Encrypt data \param in the input data to encrypt \param alg the encryption algorithm to use */ virtual SecureArray encrypt(const SecureArray &in, EncryptionAlgorithm alg); /** Decrypt data \param in the input data to decrypt \param out pointer to an array to store the plaintext result \param alg the encryption algorithm used to generate the input data */ virtual bool decrypt(const SecureArray &in, SecureArray *out, EncryptionAlgorithm alg); /** Begin a signing operation \param alg the signature algorithm to use \param format the signature format to use */ virtual void startSign(SignatureAlgorithm alg, SignatureFormat format); /** Begin a verify operation \param alg the signature algorithm used by the input signature \param format the signature format used by the input signature */ virtual void startVerify(SignatureAlgorithm alg, SignatureFormat format); /** Process the plaintext input data for either signing or verifying, whichever operation is active. \param in the input data to process */ virtual void update(const MemoryRegion &in); /** Complete a signing operation, and return the signature value If there is an error signing, an empty array is returned. */ virtual QByteArray endSign(); /** Complete a verify operation, and return true if successful If there is an error verifying, this function returns false. \param sig the signature to verify with the input data */ virtual bool endVerify(const QByteArray &sig); /** Compute a symmetric key based on this private key and some other public key Essentially for Diffie-Hellman only. \param theirs the other side (public key) to be used for key generation. */ virtual SymmetricKey deriveKey(const PKeyBase &theirs); Q_SIGNALS: /** Emitted when an asynchronous operation completes on this key. Such operations will be documented that they emit this signal. */ void finished(); }; /** \class RSAContext qcaprovider.h QtCrypto RSA provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want RSAPublicKey or RSAPrivateKey instead. \ingroup ProviderAPI */ class QCA_EXPORT RSAContext : public PKeyBase { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context */ RSAContext(Provider *p) : PKeyBase(p, QStringLiteral("rsa")) {} /** Generate an RSA private key If \a block is true, then this function blocks until completion. Otherwise, this function returns immediately and finished() is emitted when the operation completes. If an error occurs during generation, then the operation will complete and isNull() will return true. \param bits the length of the key to generate, in bits \param exp the exponent to use for generation \param block whether to use blocking mode */ virtual void createPrivate(int bits, int exp, bool block) = 0; /** Create an RSA private key based on the five components \param n the N parameter \param e the public exponent \param p the P parameter \param q the Q parameter \param d the D parameter */ virtual void createPrivate(const BigInteger &n, const BigInteger &e, const BigInteger &p, const BigInteger &q, const BigInteger &d) = 0; /** Create an RSA public key based on the two public components \param n the N parameter \param e the public exponent */ virtual void createPublic(const BigInteger &n, const BigInteger &e) = 0; /** Returns the public N component of this RSA key */ virtual BigInteger n() const = 0; /** Returns the public E component of this RSA key */ virtual BigInteger e() const = 0; /** Returns the private P component of this RSA key */ virtual BigInteger p() const = 0; /** Returns the private Q component of this RSA key */ virtual BigInteger q() const = 0; /** Returns the private D component of this RSA key */ virtual BigInteger d() const = 0; }; /** \class DSAContext qcaprovider.h QtCrypto DSA provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want DSAPublicKey or DSAPrivateKey instead. \ingroup ProviderAPI */ class QCA_EXPORT DSAContext : public PKeyBase { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context */ DSAContext(Provider *p) : PKeyBase(p, QStringLiteral("dsa")) {} /** Generate a DSA private key If \a block is true, then this function blocks until completion. Otherwise, this function returns immediately and finished() is emitted when the operation completes. If an error occurs during generation, then the operation will complete and isNull() will return true. \param domain the domain values to use for generation \param block whether to use blocking mode */ virtual void createPrivate(const DLGroup &domain, bool block) = 0; /** Create a DSA private key based on its numeric components \param domain the domain values to use for generation \param y the public Y component \param x the private X component */ virtual void createPrivate(const DLGroup &domain, const BigInteger &y, const BigInteger &x) = 0; /** Create a DSA public key based on its numeric components \param domain the domain values to use for generation \param y the public Y component */ virtual void createPublic(const DLGroup &domain, const BigInteger &y) = 0; /** Returns the public domain component of this DSA key */ virtual DLGroup domain() const = 0; /** Returns the public Y component of this DSA key */ virtual BigInteger y() const = 0; /** Returns the private X component of this DSA key */ virtual BigInteger x() const = 0; }; /** \class DHContext qcaprovider.h QtCrypto Diffie-Hellman provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want DHPublicKey or DHPrivateKey instead. \ingroup ProviderAPI */ class QCA_EXPORT DHContext : public PKeyBase { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context */ DHContext(Provider *p) : PKeyBase(p, QStringLiteral("dh")) {} /** Generate a Diffie-Hellman private key If \a block is true, then this function blocks until completion. Otherwise, this function returns immediately and finished() is emitted when the operation completes. If an error occurs during generation, then the operation will complete and isNull() will return true. \param domain the domain values to use for generation \param block whether to use blocking mode */ virtual void createPrivate(const DLGroup &domain, bool block) = 0; /** Create a Diffie-Hellman private key based on its numeric components \param domain the domain values to use for generation \param y the public Y component \param x the private X component */ virtual void createPrivate(const DLGroup &domain, const BigInteger &y, const BigInteger &x) = 0; /** Create a Diffie-Hellman public key based on its numeric components \param domain the domain values to use for generation \param y the public Y component */ virtual void createPublic(const DLGroup &domain, const BigInteger &y) = 0; /** Returns the public domain component of this Diffie-Hellman key */ virtual DLGroup domain() const = 0; /** Returns the public Y component of this Diffie-Hellman key */ virtual BigInteger y() const = 0; /** Returns the private X component of this Diffie-Hellman key */ virtual BigInteger x() const = 0; }; /** \class PKeyContext qcaprovider.h QtCrypto Public key container provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want PKey, PublicKey, or PrivateKey instead. This object "holds" a public key object. By default it contains no key (key() returns 0), but you can put a key into it with setKey(), or you can call an import function such as publicFromDER(). \ingroup ProviderAPI */ class QCA_EXPORT PKeyContext : public BasicContext { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context */ PKeyContext(Provider *p) : BasicContext(p, QStringLiteral("pkey")) {} /** Returns a list of supported public key types */ virtual QList supportedTypes() const = 0; /** Returns a list of public key types that can be serialized and deserialized into DER and PEM format */ virtual QList supportedIOTypes() const = 0; /** Returns a list of password-based encryption algorithms that are supported for private key serialization and deserialization */ virtual QList supportedPBEAlgorithms() const = 0; /** Returns the key held by this object, or 0 if there is no key */ virtual PKeyBase *key() = 0; /** Returns the key held by this object, or 0 if there is no key */ virtual const PKeyBase *key() const = 0; /** Sets the key for this object. If this object already had a key, then the old one is destructed. This object takes ownership of the key. \param key the key to be set for this object */ virtual void setKey(PKeyBase *key) = 0; /** Attempt to import a key from another provider. Returns true if successful, otherwise false. Generally this function is used if the specified key's provider does not support serialization, but your provider does. The call to this function would then be followed by an export function, such as publicToDER(). \param key the key to be imported */ virtual bool importKey(const PKeyBase *key) = 0; /** Convert a public key to DER format, and return the value Returns an empty array on error. */ virtual QByteArray publicToDER() const; /** Convert a public key to PEM format, and return the value Returns an empty string on error. */ virtual QString publicToPEM() const; /** Read DER-formatted input and convert it into a public key Returns QCA::ConvertGood if successful, otherwise some error value. \param a the input data */ virtual ConvertResult publicFromDER(const QByteArray &a); /** Read PEM-formatted input and convert it into a public key Returns QCA::ConvertGood if successful, otherwise some error value. \param s the input data */ virtual ConvertResult publicFromPEM(const QString &s); /** Convert a private key to DER format, and return the value Returns an empty array on error. \param passphrase the passphrase to encode the result with, or an empty array if no encryption is desired \param pbe the encryption algorithm to use, if applicable */ virtual SecureArray privateToDER(const SecureArray &passphrase, PBEAlgorithm pbe) const; /** Convert a private key to PEM format, and return the value Returns an empty string on error. \param passphrase the passphrase to encode the result with, or an empty array if no encryption is desired \param pbe the encryption algorithm to use, if applicable */ virtual QString privateToPEM(const SecureArray &passphrase, PBEAlgorithm pbe) const; /** Read DER-formatted input and convert it into a private key Returns QCA::ConvertGood if successful, otherwise some error value. \param a the input data \param passphrase the passphrase needed to decrypt, if applicable */ virtual ConvertResult privateFromDER(const SecureArray &a, const SecureArray &passphrase); /** Read PEM-formatted input and convert it into a private key Returns QCA::ConvertGood if successful, otherwise some error value. \param s the input data \param passphrase the passphrase needed to decrypt, if applicable */ virtual ConvertResult privateFromPEM(const QString &s, const SecureArray &passphrase); }; /** \class CertBase qcaprovider.h QtCrypto X.509 certificate and certificate request provider base \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want Certificate, CertificateRequest, or CRL instead. \ingroup ProviderAPI */ class QCA_EXPORT CertBase : public BasicContext { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context \param type the type of certificate-like object provided by this context */ CertBase(Provider *p, const QString &type) : BasicContext(p, type) {} /** Convert this object to DER format, and return the value Returns an empty array on error. */ virtual QByteArray toDER() const = 0; /** Convert this object to PEM format, and return the value Returns an empty string on error. */ virtual QString toPEM() const = 0; /** Read DER-formatted input and convert it into this object Returns QCA::ConvertGood if successful, otherwise some error value. \param a the input data */ virtual ConvertResult fromDER(const QByteArray &a) = 0; /** Read PEM-formatted input and convert it into this object Returns QCA::ConvertGood if successful, otherwise some error value. \param s the input data */ virtual ConvertResult fromPEM(const QString &s) = 0; }; /** \class CertContextProps qcaprovider.h QtCrypto X.509 certificate or certificate request properties \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want Certificate or CertificateRequest instead. Some fields are only for certificates or only for certificate requests, and these fields are noted. \ingroup ProviderAPI */ class QCA_EXPORT CertContextProps { public: /** The X.509 certificate version, usually 3 This field is for certificates only. */ int version; /** The time the certificate becomes valid (often the time of create) This field is for certificates only. */ QDateTime start; /** The time the certificate expires This field is for certificates only. */ QDateTime end; /** The subject information */ CertificateInfoOrdered subject; /** The issuer information This field is for certificates only. */ CertificateInfoOrdered issuer; /** The constraints */ Constraints constraints; /** The policies */ QStringList policies; /** A list of URIs for CRLs This field is for certificates only. */ QStringList crlLocations; /** A list of URIs for issuer certificates This field is for certificates only. */ QStringList issuerLocations; /** A list of URIs for OCSP services This field is for certificates only. */ QStringList ocspLocations; /** The certificate serial number This field is for certificates only. */ BigInteger serial; /** True if the certificate is a CA or the certificate request is requesting to be a CA, otherwise false */ bool isCA; /** True if the certificate is self-signed This field is for certificates only. */ bool isSelfSigned; /** The path limit */ int pathLimit; /** The signature data */ QByteArray sig; /** The signature algorithm used to create the signature */ SignatureAlgorithm sigalgo; /** The subject id This field is for certificates only. */ QByteArray subjectId; /** The issuer id This field is for certificates only. */ QByteArray issuerId; /** The SPKAC challenge value This field is for certificate requests only. */ QString challenge; /** The format used for the certificate request This field is for certificate requests only. */ CertificateRequestFormat format; }; /** \class CRLContextProps qcaprovider.h QtCrypto X.509 certificate revocation list properties \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want CRL instead. For efficiency and simplicity, the members are directly accessed. \ingroup ProviderAPI */ class QCA_EXPORT CRLContextProps { public: /** The issuer information of the CRL */ CertificateInfoOrdered issuer; /** The CRL number, which increases at each update */ int number; /** The time this CRL was created */ QDateTime thisUpdate; /** The time this CRL expires, and the next CRL should be fetched */ QDateTime nextUpdate; /** The revoked entries */ QList revoked; /** The signature data of the CRL */ QByteArray sig; /** The signature algorithm used by the issuer to sign the CRL */ SignatureAlgorithm sigalgo; /** The issuer id */ QByteArray issuerId; }; class CRLContext; /** \class CertContext qcaprovider.h QtCrypto X.509 certificate provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want Certificate instead. \ingroup ProviderAPI */ class QCA_EXPORT CertContext : public CertBase { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context */ CertContext(Provider *p) : CertBase(p, QStringLiteral("cert")) {} /** Create a self-signed certificate based on the given options and private key. Returns true if successful, otherwise false. If successful, this object becomes the self-signed certificate. If unsuccessful, this object is considered to be in an uninitialized state. \param opts the options to set on the certificate \param priv the key to be used to sign the certificate */ virtual bool createSelfSigned(const CertificateOptions &opts, const PKeyContext &priv) = 0; /** Returns a pointer to the properties of this certificate */ virtual const CertContextProps *props() const = 0; /** Returns true if this certificate is equal to another certificate, otherwise false \param other the certificate to compare with */ virtual bool compare(const CertContext *other) const = 0; /** Returns a copy of this certificate's public key. The caller is responsible for deleting it. */ virtual PKeyContext *subjectPublicKey() const = 0; /** Returns true if this certificate is an issuer of another certificate, otherwise false \param other the issued certificate to check */ virtual bool isIssuerOf(const CertContext *other) const = 0; /** Validate this certificate This function is blocking. \param trusted list of trusted certificates \param untrusted list of untrusted certificates (can be empty) \param crls list of CRLs (can be empty) \param u the desired usage for this certificate \param vf validation options */ virtual Validity validate(const QList &trusted, const QList &untrusted, const QList &crls, UsageMode u, ValidateFlags vf) const = 0; /** Validate a certificate chain. This function makes no use of the certificate represented by this object, and it can be used even if this object is in an uninitialized state. This function is blocking. \param chain list of certificates in the chain, starting with the user certificate. It is not necessary for the chain to contain the final root certificate. \param trusted list of trusted certificates \param crls list of CRLs (can be empty) \param u the desired usage for the user certificate in the chain \param vf validation options */ virtual Validity validate_chain(const QList &chain, const QList &trusted, const QList &crls, UsageMode u, ValidateFlags vf) const = 0; }; /** \class CSRContext qcaprovider.h QtCrypto X.509 certificate request provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want CertificateRequest instead. \ingroup ProviderAPI */ class QCA_EXPORT CSRContext : public CertBase { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context */ CSRContext(Provider *p) : CertBase(p, QStringLiteral("csr")) {} /** Returns true if the provider of this object supports the specified format, otherwise false \param f the format to test for support for. */ virtual bool canUseFormat(CertificateRequestFormat f) const = 0; /** Create a certificate request based on the given options and private key. Returns true if successful, otherwise false. If successful, this object becomes the certificate request. If unsuccessful, this object is considered to be in an uninitialized state. \param opts the options to set on the certificate \param priv the key to be used to sign the certificate */ virtual bool createRequest(const CertificateOptions &opts, const PKeyContext &priv) = 0; /** Returns a pointer to the properties of this certificate request */ virtual const CertContextProps *props() const = 0; /** Returns true if this certificate request is equal to another certificate request, otherwise false \param other the certificate request to compare with */ virtual bool compare(const CSRContext *other) const = 0; /** Returns a copy of this certificate request's public key. The caller is responsible for deleting it. */ virtual PKeyContext *subjectPublicKey() const = 0; /** Convert this certificate request to Netscape SPKAC format, and return the value Returns an empty string on error. */ virtual QString toSPKAC() const = 0; /** Read Netscape SPKAC input and convert it into a certificate request Returns QCA::ConvertGood if successful, otherwise some error value. \param s the input data */ virtual ConvertResult fromSPKAC(const QString &s) = 0; }; /** \class CRLContext qcaprovider.h QtCrypto X.509 certificate revocation list provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want CRL instead. \ingroup ProviderAPI */ class QCA_EXPORT CRLContext : public CertBase { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context */ CRLContext(Provider *p) : CertBase(p, QStringLiteral("crl")) {} /** Returns a pointer to the properties of this CRL */ virtual const CRLContextProps *props() const = 0; /** Returns true if this CRL is equal to another CRL, otherwise false \param other the CRL to compare with */ virtual bool compare(const CRLContext *other) const = 0; }; /** \class CertCollectionContext qcaprovider.h QtCrypto X.509 certificate collection provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want CertificateCollection instead. \ingroup ProviderAPI */ class QCA_EXPORT CertCollectionContext : public BasicContext { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context */ CertCollectionContext(Provider *p) : BasicContext(p, QStringLiteral("certcollection")) {} /** Create PKCS#7 DER output based on the input certificates and CRLs Returns an empty array on error. \param certs list of certificates to store in the output \param crls list of CRLs to store in the output */ virtual QByteArray toPKCS7(const QList &certs, const QList &crls) const = 0; /** Read PKCS#7 DER input and convert it into a list of certificates and CRLs The caller is responsible for deleting the returned items. Returns QCA::ConvertGood if successful, otherwise some error value. \param a the input data \param certs the destination list for the certificates \param crls the destination list for the CRLs */ virtual ConvertResult fromPKCS7(const QByteArray &a, QList *certs, QList *crls) const = 0; }; /** \class CAContext qcaprovider.h QtCrypto X.509 certificate authority provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want CertificateAuthority instead. \ingroup ProviderAPI */ class QCA_EXPORT CAContext : public BasicContext { Q_OBJECT public: /** Standard constructor \param p the Provider associated with this context */ CAContext(Provider *p) : BasicContext(p, QStringLiteral("ca")) {} /** Prepare the object for usage This must be called before any CA operations are performed. \param cert the certificate of the CA \param priv the private key of the CA */ virtual void setup(const CertContext &cert, const PKeyContext &priv) = 0; /** Returns a copy of the CA's certificate. The caller is responsible for deleting it. */ virtual CertContext *certificate() const = 0; /** Issue a certificate based on a certificate request, and return the certificate. The caller is responsible for deleting it. \param req the certificate request \param notValidAfter the expiration date */ virtual CertContext *signRequest(const CSRContext &req, const QDateTime ¬ValidAfter) const = 0; /** Issue a certificate based on a public key and options, and return the certificate. The caller is responsible for deleting it. \param pub the public key of the certificate \param opts the options to use for generation */ virtual CertContext *createCertificate(const PKeyContext &pub, const CertificateOptions &opts) const = 0; /** Create a new CRL and return it. The caller is responsible for deleting it. The CRL has no entries in it. \param nextUpdate the expiration date of the CRL */ virtual CRLContext *createCRL(const QDateTime &nextUpdate) const = 0; /** Update an existing CRL, by examining an old one and creating a new one based on it. The new CRL is returned, and the caller is responsible for deleting it. \param crl an existing CRL issued by this CA \param entries the list of revoked entries \param nextUpdate the expiration date of the new CRL */ virtual CRLContext *updateCRL(const CRLContext &crl, const QList &entries, const QDateTime &nextUpdate) const = 0; }; /** \class PKCS12Context qcaprovider.h QtCrypto PKCS#12 provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want KeyBundle instead. \ingroup ProviderAPI */ class QCA_EXPORT PKCS12Context : public BasicContext { Q_OBJECT public: /** Standard constructor \param p the Provider associated with this context */ PKCS12Context(Provider *p) : BasicContext(p, QStringLiteral("pkcs12")) {} /** Create PKCS#12 DER output based on a set of input items Returns an empty array on error. \param name the friendly name of the data \param chain the certificate chain to store \param priv the private key to store \param passphrase the passphrase to encrypt the PKCS#12 data with */ virtual QByteArray toPKCS12(const QString &name, const QList &chain, const PKeyContext &priv, const SecureArray &passphrase) const = 0; /** Read PKCS#12 DER input and convert it into a set of output items The caller is responsible for deleting the returned items. Returns QCA::ConvertGood if successful, otherwise some error value. \param in the input data \param passphrase the passphrase needed to decrypt the input data \param name the destination string for the friendly name \param chain the destination list for the certificate chain \param priv address of a pointer to accept the private key */ virtual ConvertResult fromPKCS12(const QByteArray &in, const SecureArray &passphrase, QString *name, QList *chain, PKeyContext **priv) const = 0; }; /** \class PGPKeyContextProps qcaprovider.h QtCrypto OpenPGP key properties \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want PGPKey instead. For efficiency and simplicity, the members are directly accessed. \ingroup ProviderAPI */ class QCA_EXPORT PGPKeyContextProps { public: /** The key id */ QString keyId; /** List of user id strings for the key, the first one being the primary user id */ QStringList userIds; /** True if this key is a secret key, otherwise false */ bool isSecret; /** The time the key was created */ QDateTime creationDate; /** The time the key expires */ QDateTime expirationDate; /** The hex fingerprint of the key The format is all lowercase with no spaces. */ QString fingerprint; /** True if this key is in a keyring (and thus usable), otherwise false */ bool inKeyring; /** True if this key is trusted (e.g. signed by the keyring owner or via some web-of-trust), otherwise false */ bool isTrusted; }; /** \class PGPKeyContext qcaprovider.h QtCrypto OpenPGP key provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want PGPKey instead. \ingroup ProviderAPI */ class QCA_EXPORT PGPKeyContext : public BasicContext { Q_OBJECT public: /** Standard constructor \param p the Provider associated with this context */ PGPKeyContext(Provider *p) : BasicContext(p, QStringLiteral("pgpkey")) {} /** Returns a pointer to the properties of this key */ virtual const PGPKeyContextProps *props() const = 0; /** Convert the key to binary format, and return the value */ virtual QByteArray toBinary() const = 0; /** Convert the key to ascii-armored format, and return the value */ virtual QString toAscii() const = 0; /** Read binary input and convert it into a key Returns QCA::ConvertGood if successful, otherwise some error value. \param a the input data */ virtual ConvertResult fromBinary(const QByteArray &a) = 0; /** Read ascii-armored input and convert it into a key Returns QCA::ConvertGood if successful, otherwise some error value. \param s the input data */ virtual ConvertResult fromAscii(const QString &s) = 0; }; /** \class KeyStoreEntryContext qcaprovider.h QtCrypto KeyStoreEntry provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want KeyStoreEntry instead. \ingroup ProviderAPI */ class QCA_EXPORT KeyStoreEntryContext : public BasicContext { Q_OBJECT public: /** Standard constructor \param p the Provider associated with this context */ KeyStoreEntryContext(Provider *p) : BasicContext(p, QStringLiteral("keystoreentry")) {} /** Returns the entry type */ virtual KeyStoreEntry::Type type() const = 0; /** Returns the entry id This id must be unique among all other entries in the same store. */ virtual QString id() const = 0; /** Returns the name of this entry */ virtual QString name() const = 0; /** Returns the id of the store that contains this entry */ virtual QString storeId() const = 0; /** Returns the name of the store that contains this entry */ virtual QString storeName() const = 0; /** Returns true if the private key of this entry is present for use */ virtual bool isAvailable() const; /** Serialize the information about this entry This allows the entry object to be restored later, even if the store that contains it is not present. \sa KeyStoreListContext::entryPassive() */ virtual QString serialize() const = 0; /** If this entry is of type KeyStoreEntry::TypeKeyBundle, this function returns the KeyBundle of the entry */ virtual KeyBundle keyBundle() const; /** If this entry is of type KeyStoreEntry::TypeCertificate, this function returns the Certificate of the entry */ virtual Certificate certificate() const; /** If this entry is of type KeyStoreEntry::TypeCRL, this function returns the CRL of the entry */ virtual CRL crl() const; /** If this entry is of type KeyStoreEntry::TypePGPSecretKey, this function returns the secret PGPKey of the entry */ virtual PGPKey pgpSecretKey() const; /** If this entry is of type KeyStoreEntry::TypePGPPublicKey or KeyStoreEntry::TypePGPSecretKey, this function returns the public PGPKey of the entry */ virtual PGPKey pgpPublicKey() const; /** Attempt to ensure the private key of this entry is usable and accessible, potentially prompting the user and/or performing a login to a token device. Returns true if the entry is now accessible, or false if the entry cannot be made accessible. This function is blocking. */ virtual bool ensureAccess(); }; /** \class KeyStoreListContext qcaprovider.h QtCrypto KeyStore provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want KeyStore instead. \ingroup ProviderAPI */ class QCA_EXPORT KeyStoreListContext : public Provider::Context { Q_OBJECT public: /** Standard constructor \param p the Provider associated with this context */ KeyStoreListContext(Provider *p) : Provider::Context(p, QStringLiteral("keystorelist")) {} /** Starts the keystore provider */ virtual void start(); /** Enables or disables update events The updated() and storeUpdated() signals might not be emitted if updates are not enabled. \param enabled whether update notifications are enabled (true) or disabled (false) */ virtual void setUpdatesEnabled(bool enabled); /** Returns a list of integer context ids, each representing a keystore instance If a keystore becomes unavailable and then later becomes available again (for example, if a smart card is removed and then the same one is inserted again), the integer context id must be different than last time. */ virtual QList keyStores() = 0; /** Returns the type of the specified store, or -1 if the integer context id is invalid \param id the id for the store context */ virtual KeyStore::Type type(int id) const = 0; /** Returns the string id of the store, or an empty string if the integer context id is invalid The string id of the store should be unique to a single store, and it should persist between availability/unavailability. For example, a smart card that is removed and inserted again should have the same string id (despite having a new integer context id). \param id the id for the store context */ virtual QString storeId(int id) const = 0; /** Returns the friendly name of the store, or an empty string if the integer context id is invalid \param id the id for the store context */ virtual QString name(int id) const = 0; /** Returns true if the store is read-only If the integer context id is invalid, this function should return true. \param id the id for the store context */ virtual bool isReadOnly(int id) const; /** Returns the types supported by the store, or an empty list if the integer context id is invalid This function should return all supported types, even if the store doesn't actually contain entries for all of the types. \param id the id for the store context */ virtual QList entryTypes(int id) const = 0; /** Returns the entries of the store, or an empty list if the integer context id is invalid The caller is responsible for deleting the returned entry objects. \param id the id for the store context */ virtual QList entryList(int id) = 0; /** Returns a single entry in the store, if the entry id is already known. If the entry does not exist, the function returns 0. The caller is responsible for deleting the returned entry object. \param id the id for the store context \param entryId the entry to retrieve */ virtual KeyStoreEntryContext *entry(int id, const QString &entryId); /** Returns a single entry, created from the serialization string of a previous entry (using KeyStoreEntryContext::serialize()). If the serialization string cannot be parsed by this provider, or the entry cannot otherwise be created, the function returns 0. The caller is responsible for deleting the returned entry object. This function must be thread-safe. \param serialized the serialized data to create the entry from */ virtual KeyStoreEntryContext *entryPassive(const QString &serialized); /** Write a KeyBundle to the store Returns the entry id of the new item, or an empty string if there was an error writing the item. \param id the id for the store context \param kb the key bundle to add to the store */ virtual QString writeEntry(int id, const KeyBundle &kb); /** Write a Certificate to the store Returns the entry id of the new item, or an empty string if there was an error writing the item. \param id the id for the store context \param cert the certificate to add to the store */ virtual QString writeEntry(int id, const Certificate &cert); /** Write a CRL to the store Returns the entry id of the new item, or an empty string if there was an error writing the item. \param id the id for the store context \param crl the revocation list to add to the store */ virtual QString writeEntry(int id, const CRL &crl); /** Write a PGPKey to the store Returns the entry id of the new item, or an empty string if there was an error writing the item. \param id the id for the store context \param key the PGP key to add to the store */ virtual QString writeEntry(int id, const PGPKey &key); /** Remove an entry from the store Returns true if the entry is successfully removed, otherwise false. \param id the id for the store context \param entryId the entry to remove from the store */ virtual bool removeEntry(int id, const QString &entryId); Q_SIGNALS: /** Emit this when the provider is busy looking for keystores. The provider goes into a busy state when it has reason to believe there are keystores present, but it still needs to check or query some devices to see for sure. For example, if a smart card is inserted, then the provider may immediately go into a busy state upon detecting the insert. However, it may take some seconds before the smart card information can be queried and reported by the provider. Once the card is queried successfully, the provider would leave the busy state and report the new keystore. When this object is first started with start(), it is assumed to be in the busy state, so there is no need to emit this signal at the beginning. */ void busyStart(); /** Emit this to leave the busy state When this object is first started with start(), it is assumed to be in the busy state. You must emit busyEnd() at some point, or QCA will never ask you about keystores. */ void busyEnd(); /** Indicates the list of keystores has changed, and that QCA should call keyStores() to obtain the latest list */ void updated(); /** Emitted when there is diagnostic text to report \param str the diagnostic text */ void diagnosticText(const QString &str); /** Indicates that the entry list of a keystore has changed (entries added, removed, or modified) \param id the id of the key store that has changed */ void storeUpdated(int id); }; /** \class TLSSessionContext qcaprovider.h QtCrypto TLS "session" provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want TLSSession instead. \ingroup ProviderAPI */ class QCA_EXPORT TLSSessionContext : public BasicContext { Q_OBJECT public: /** Standard constructor \param p the Provider associated with this context */ TLSSessionContext(Provider *p) : BasicContext(p, QStringLiteral("tlssession")) {} }; /** \class TLSContext qcaprovider.h QtCrypto TLS provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want TLS instead. \ingroup ProviderAPI */ class QCA_EXPORT TLSContext : public Provider::Context { Q_OBJECT public: /** \class QCA::TLSContext::SessionInfo qcaprovider.h QtCrypto Information about an active TLS connection For efficiency and simplicity, the members are directly accessed. \ingroup ProviderAPI */ class SessionInfo { public: /** True if the TLS connection is compressed, otherwise false */ bool isCompressed; /** The TLS protocol version being used for this connection */ TLS::Version version; /** The cipher suite being used for this connection \sa TLSContext::supportedCipherSuites() */ QString cipherSuite; /** The bit size of the cipher used for this connection */ int cipherBits; /** The maximum bit size possible of the cipher used for this connection */ int cipherMaxBits; /** Pointer to the id of this TLS session, for use with resuming */ TLSSessionContext *id; }; /** Result of a TLS operation */ enum Result { Success, ///< Operation completed Error, ///< Operation failed Continue ///< More data needed to complete operation }; /** Standard constructor \param p the Provider associated with this context \param type the name of the type of feature that supported by this context */ TLSContext(Provider *p, const QString &type) : Provider::Context(p, type) {} /** Reset the object to its initial state */ virtual void reset() = 0; /** Returns a list of supported cipher suites for the specified SSL/TLS version. The cipher suites are specified as strings, for example: "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA" (without quotes). \param version the version of TLS to search for */ virtual QStringList supportedCipherSuites(const TLS::Version &version) const = 0; /** Returns true if the provider supports compression */ virtual bool canCompress() const = 0; /** Returns true if the provider supports server name indication */ virtual bool canSetHostName() const = 0; /** Returns the maximum SSF supported by this provider */ virtual int maxSSF() const = 0; /** Configure a new session This function will be called before any other configuration functions. \param serverMode whether to operate as a server (true) or client (false) \param hostName the hostname to use \param compress whether to compress (true) or not (false) */ virtual void setup(bool serverMode, const QString &hostName, bool compress) = 0; /** Set the constraints of the session using SSF values This function will be called before start(). \param minSSF the minimum strength factor that is acceptable \param maxSSF the maximum strength factor that is acceptable */ virtual void setConstraints(int minSSF, int maxSSF) = 0; /** \overload Set the constraints of the session using a cipher suite list This function will be called before start(). \param cipherSuiteList the list of cipher suites that may be used for this session. \sa supportedCipherSuites */ virtual void setConstraints(const QStringList &cipherSuiteList) = 0; /** Set the list of trusted certificates This function may be called at any time. \param trusted the trusted certificates and CRLs to be used. */ virtual void setTrustedCertificates(const CertificateCollection &trusted) = 0; /** Set the list of acceptable issuers This function may be called at any time. This function is for server mode only. \param issuerList the list of issuers that may be used */ virtual void setIssuerList(const QList &issuerList) = 0; /** Set the local certificate This function may be called at any time. \param cert the certificate and associated trust chain \param key the private key for the local certificate */ virtual void setCertificate(const CertificateChain &cert, const PrivateKey &key) = 0; /** Set the TLS session id, for session resuming This function will be called before start(). \param id the session identification */ virtual void setSessionId(const TLSSessionContext &id) = 0; /** Sets the session to the shutdown state. The actual shutdown operation will happen at a future call to update(). This function is for normal TLS only (not DTLS). */ virtual void shutdown() = 0; /** Set the maximum transmission unit size This function is for DTLS only. \param size the maximum number of bytes in a datagram */ virtual void setMTU(int size); /** Begins the session, starting with the handshake This function returns immediately, and completion is signaled with the resultsReady() signal. On completion, the result() function will return Success if the TLS session is able to begin, or Error if there is a failure to initialize the TLS subsystem. If successful, the session is now in the handshake state, and update() will be called repeatedly until the session ends. */ virtual void start() = 0; /** Performs one iteration of the TLS session processing This function returns immediately, and completion is signaled with the resultsReady() signal. If the session is in a handshake state, result() and to_net() will be valid. If result() is Success, then the session is now in the connected state. If the session is in a shutdown state, result() and to_net() will be valid. If result() is Success, then the session has ended. If the session is in a connected state, result(), to_net(), encoded(), to_app(), and eof() are valid. The result() function will return Success or Error. Note that eof() does not apply to DTLS. For DTLS, this function operates with single packets. Many update() operations must be performed repeatedly to exchange multiple packets. \param from_net the data from the "other side" of the connection \param from_app the data from the application of the protocol */ virtual void update(const QByteArray &from_net, const QByteArray &from_app) = 0; /** Waits for a start() or update() operation to complete. In this case, the resultsReady() signal is not emitted. Returns true if the operation completed or false if this function times out. This function is blocking. \param msecs number of milliseconds to wait (-1 to wait forever) */ virtual bool waitForResultsReady(int msecs) = 0; /** Returns the result code of an operation */ virtual Result result() const = 0; /** Returns data that should be sent across the network */ virtual QByteArray to_net() = 0; /** Returns the number of bytes of plaintext data that is encoded inside of to_net() */ virtual int encoded() const = 0; /** Returns data that is decoded from the network and should be processed by the application */ virtual QByteArray to_app() = 0; /** Returns true if the peer has closed the stream */ virtual bool eof() const = 0; /** Returns true if the TLS client hello has been received This is only valid if a handshake is in progress or completed. */ virtual bool clientHelloReceived() const = 0; /** Returns true if the TLS server hello has been received This is only valid if a handshake is in progress or completed. */ virtual bool serverHelloReceived() const = 0; /** Returns the host name sent by the client using server name indication (server mode only) This is only valid if a handshake is in progress or completed. */ virtual QString hostName() const = 0; /** Returns true if the peer is requesting a certificate This is only valid if a handshake is in progress or completed. */ virtual bool certificateRequested() const = 0; /** Returns the issuer list sent by the server (client mode only) This is only valid if a handshake is in progress or completed. */ virtual QList issuerList() const = 0; /** Returns the QCA::Validity of the peer certificate This is only valid if a handshake is completed. */ virtual Validity peerCertificateValidity() const = 0; /** Returns the peer certificate chain This is only valid if a handshake is completed. */ virtual CertificateChain peerCertificateChain() const = 0; /** Returns information about the active TLS session This is only valid if a handshake is completed. */ virtual SessionInfo sessionInfo() const = 0; /** Returns any unprocessed network input data This is only valid after a successful shutdown. */ virtual QByteArray unprocessed() = 0; Q_SIGNALS: /** Emit this when a start() or update() operation has completed. */ void resultsReady(); /** Emit this to force the application to call update(), even with empty arguments. */ void dtlsTimeout(); }; /** \class SASLContext qcaprovider.h QtCrypto SASL provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want SASL instead. \ingroup ProviderAPI */ class QCA_EXPORT SASLContext : public Provider::Context { Q_OBJECT public: /** \class QCA::SASLContext::HostPort qcaprovider.h QtCrypto Convenience class to hold an IP address and an associated port For efficiency and simplicity, the members are directly accessed. \ingroup ProviderAPI */ class HostPort { public: /** The IP address */ QString addr; /** The port */ quint16 port; }; /** Result of a SASL operation */ enum Result { Success, ///< Operation completed Error, ///< Operation failed Params, ///< Parameters are needed to complete authentication AuthCheck, ///< Client login can be inspected (server only) Continue ///< More steps needed to complete authentication }; /** Standard constructor \param p the Provider associated with this context */ SASLContext(Provider *p) : Provider::Context(p, QStringLiteral("sasl")) {} /** Reset the object to its initial state */ virtual void reset() = 0; /** Configure a new session This function will be called before any other configuration functions. \param service the name of the network service being provided by this application, which can be used by the SASL system for policy control. Examples: "imap", "xmpp" \param host the hostname that the application is interacting with or as \param local pointer to a HostPort representing the local end of a network socket, or 0 if this information is unknown or not available \param remote pointer to a HostPort representing the peer end of a network socket, or 0 if this information is unknown or not available \param ext_id the id to be used for SASL EXTERNAL (client only) \param ext_ssf the SSF of the external authentication channel (client only) */ virtual void setup(const QString &service, const QString &host, const HostPort *local, const HostPort *remote, const QString &ext_id, int ext_ssf) = 0; /** Set the constraints of the session using SSF values This function will be called before startClient() or startServer(). \param f the flags to use \param minSSF the minimum strength factor that is acceptable \param maxSSF the maximum strength factor that is acceptable */ virtual void setConstraints(SASL::AuthFlags f, int minSSF, int maxSSF) = 0; /** Begins the session in client mode, starting with the authentication This function returns immediately, and completion is signaled with the resultsReady() signal. On completion, result(), mech(), haveClientInit(), and stepData() will be valid. If result() is Success, then the session is now in the connected state. \param mechlist the list of mechanisms \param allowClientSendFirst whether the client sends first (true) or the server sends first (false) */ virtual void startClient(const QStringList &mechlist, bool allowClientSendFirst) = 0; /** Begins the session in server mode, starting with the authentication This function returns immediately, and completion is signaled with the resultsReady() signal. On completion, result() and mechlist() will be valid. The result() function will return Success or Error. If the result is Success, then serverFirstStep() will be called next. \param realm the realm to authenticate in \param disableServerSendLast whether the client sends first (true) or the server sends first (false) */ virtual void startServer(const QString &realm, bool disableServerSendLast) = 0; /** Finishes server startup This function returns immediately, and completion is signaled with the resultsReady() signal. On completion, result() and stepData() will be valid. If result() is Success, then the session is now in the connected state. \param mech the mechanism to use \param clientInit initial data from the client, or 0 if there is no such data */ virtual void serverFirstStep(const QString &mech, const QByteArray *clientInit) = 0; /** Perform another step of the SASL authentication This function returns immediately, and completion is signaled with the resultsReady() signal. On completion, result() and stepData() will be valid. \param from_net the data from the "other side" of the protocol to be used for the next step. */ virtual void nextStep(const QByteArray &from_net) = 0; /** Attempt the most recent operation again. This is used if the result() of an operation is Params or AuthCheck. This function returns immediately, and completion is signaled with the resultsReady() signal. On completion, result() and stepData() will be valid. */ virtual void tryAgain() = 0; /** Performs one iteration of the SASL security layer processing This function returns immediately, and completion is signaled with the resultsReady() signal. On completion, result(), to_net(), encoded(), and to_app() will be valid. The result() function will return Success or Error. \param from_net the data from the "other side" of the protocol \param from_app the data from the application of the protocol */ virtual void update(const QByteArray &from_net, const QByteArray &from_app) = 0; /** Waits for a startClient(), startServer(), serverFirstStep(), nextStep(), tryAgain(), or update() operation to complete. In this case, the resultsReady() signal is not emitted. Returns true if the operation completed or false if this function times out. This function is blocking. \param msecs number of milliseconds to wait (-1 to wait forever) */ virtual bool waitForResultsReady(int msecs) = 0; /** Returns the result code of an operation */ virtual Result result() const = 0; /** Returns the mechanism list (server mode only) */ virtual QStringList mechlist() const = 0; /** Returns the mechanism selected */ virtual QString mech() const = 0; /** Returns true if the client has initialization data */ virtual bool haveClientInit() const = 0; /** Returns an authentication payload for to be transmitted over the network */ virtual QByteArray stepData() const = 0; /** Returns data that should be sent across the network (for the security layer) */ virtual QByteArray to_net() = 0; /** Returns the number of bytes of plaintext data that is encoded inside of to_net() */ virtual int encoded() const = 0; /** Returns data that is decoded from the network and should be processed by the application */ virtual QByteArray to_app() = 0; /** Returns the SSF of the active SASL session This is only valid after authentication success. */ virtual int ssf() const = 0; /** Returns the reason for failure, if the authentication was not successful. This is only valid after authentication failure. */ virtual SASL::AuthCondition authCondition() const = 0; /** Returns the needed/optional client parameters This is only valid after receiving the Params result code. */ virtual SASL::Params clientParams() const = 0; /** Set some of the client parameters (pass 0 to not set a field) \param user the user name \param authzid the authorization name / role \param pass the password \param realm the realm to authenticate in */ virtual void setClientParams(const QString *user, const QString *authzid, const SecureArray *pass, const QString *realm) = 0; /** Returns the realm list (client mode only) This is only valid after receiving the Params result code and SASL::Params::canSendRealm is set to true. */ virtual QStringList realmlist() const = 0; /** Returns the username attempting to authenticate (server mode only) This is only valid after receiving the AuthCheck result code. */ virtual QString username() const = 0; /** Returns the authzid attempting to authorize (server mode only) This is only valid after receiving the AuthCheck result code. */ virtual QString authzid() const = 0; Q_SIGNALS: /** Emit this when a startClient(), startServer(), serverFirstStep(), nextStep(), tryAgain(), or update() operation has completed. */ void resultsReady(); }; /** \class MessageContext qcaprovider.h QtCrypto SecureMessage provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want SecureMessage instead. \ingroup ProviderAPI */ class QCA_EXPORT MessageContext : public Provider::Context { Q_OBJECT public: /** The type of operation being performed */ enum Operation { Encrypt, ///< Encrypt operation Decrypt, ///< Decrypt (or Decrypt and Verify) operation Sign, ///< Sign operation Verify, ///< Verify operation SignAndEncrypt ///< Sign and Encrypt operation }; /** Standard constructor \param p the Provider associated with this context \param type the name of the type of secure message to be created */ MessageContext(Provider *p, const QString &type) : Provider::Context(p, type) {} /** Returns true if the provider supports multiple signers for signature creation or signature verification */ virtual bool canSignMultiple() const = 0; /** The type of secure message (e.g. PGP or CMS) */ virtual SecureMessage::Type type() const = 0; /** Reset the object to its initial state */ virtual void reset() = 0; /** Configure a new encrypting operation \param keys the keys to be used for encryption. */ virtual void setupEncrypt(const SecureMessageKeyList &keys) = 0; /** Configure a new signing operation \param keys the keys to use for signing \param m the mode to sign in \param bundleSigner whether to bundle the signing keys (true) or not (false) \param smime whether to use smime format (true) or not (false) */ virtual void setupSign(const SecureMessageKeyList &keys, SecureMessage::SignMode m, bool bundleSigner, bool smime) = 0; /** Configure a new verify operation \param detachedSig the detached signature to use (if applicable) for verification */ virtual void setupVerify(const QByteArray &detachedSig) = 0; /** Begins the secure message operation This function returns immediately. If there is input data, update() will be called (potentially repeatedly) afterwards. Emit updated() if there is data to read, if input data has been accepted, or if the operation has finished. \param f the format of the message to be produced \param op the operation to be performed */ virtual void start(SecureMessage::Format f, Operation op) = 0; /** Provide input to the message operation \param in the data to use for the message operation */ virtual void update(const QByteArray &in) = 0; /** Extract output from the message operation */ virtual QByteArray read() = 0; /** Returns the number of input bytes accepted since the last call to update() */ virtual int written() = 0; /** Indicates the end of input */ virtual void end() = 0; /** Returns true if the operation has finished, otherwise false */ virtual bool finished() const = 0; /** Waits for the secure message operation to complete. In this case, the updated() signal is not emitted. Returns true if the operation completed or false if this function times out. This function is blocking. \param msecs number of milliseconds to wait (-1 to wait forever) */ virtual bool waitForFinished(int msecs) = 0; /** Returns true if the operation was successful This is only valid if the operation has finished. */ virtual bool success() const = 0; /** Returns the reason for failure, if the operation was not successful This is only valid if the operation has finished. */ virtual SecureMessage::Error errorCode() const = 0; /** Returns the signature, in the case of a detached signature operation This is only valid if the operation has finished. */ virtual QByteArray signature() const = 0; /** Returns the name of the hash used to generate the signature, in the case of a signature operation This is only valid if the operation has finished. */ virtual QString hashName() const = 0; /** Returns a list of signatures, in the case of a verify or decrypt and verify operation This is only valid if the operation has finished. */ virtual SecureMessageSignatureList signers() const = 0; /** Returns any diagnostic text for the operation, potentially useful to show the user in the event the operation is unsuccessful. For example, this could be the stderr output of gpg. This is only valid if the operation has finished. */ virtual QString diagnosticText() const; Q_SIGNALS: /** Emitted when there is data to read, if input data has been accepted, or if the operation has finished */ void updated(); }; /** \class SMSContext qcaprovider.h QtCrypto SecureMessageSystem provider \note This class is part of the provider plugin interface and should not be used directly by applications. You probably want SecureMessageSystem instead. \ingroup ProviderAPI */ class QCA_EXPORT SMSContext : public BasicContext { Q_OBJECT public: /** Standard constructor \param p the provider associated with this context \param type the name of the type of secure message system */ SMSContext(Provider *p, const QString &type) : BasicContext(p, type) {} /** Set the trusted certificates and for this secure message system, to be used for validation The collection may also contain CRLs. This function is only valid for CMS. \param trusted a set of trusted certificates and CRLs. */ virtual void setTrustedCertificates(const CertificateCollection &trusted); /** Set the untrusted certificates and CRLs for this secure message system, to be used for validation This function is only valid for CMS. \param untrusted a set of untrusted certificates and CRLs. */ virtual void setUntrustedCertificates(const CertificateCollection &untrusted); /** Set the private keys for this secure message system, to be used for decryption This function is only valid for CMS. \param keys the keys to be used for decryption */ virtual void setPrivateKeys(const QList &keys); /** Create a new message object for this system. The caller is responsible for deleting it. */ virtual MessageContext *createMessage() = 0; }; } #endif #endif diff --git a/plugins/qca-botan/qca-botan.cpp b/plugins/qca-botan/qca-botan.cpp index 8822ab54..d6230748 100644 --- a/plugins/qca-botan/qca-botan.cpp +++ b/plugins/qca-botan/qca-botan.cpp @@ -1,557 +1,603 @@ /* * Copyright (C) 2004 Justin Karneges * Copyright (C) 2004-2006 Brad Hards * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * */ #include #include #include #include #include #include #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0) #include #include #else #include #include #include #include #include +#include #include #endif #include #include //----------------------------------------------------------- class botanRandomContext : public QCA::RandomContext { public: botanRandomContext(QCA::Provider *p) : RandomContext(p) { } Context *clone() const { return new botanRandomContext( *this ); } QCA::SecureArray nextBytes(int size) { QCA::SecureArray buf(size); Botan::AutoSeeded_RNG rng; rng.randomize(reinterpret_cast(buf.data()), buf.size()); return buf; } }; //----------------------------------------------------------- class BotanHashContext : public QCA::HashContext { public: BotanHashContext( const QString &hashName, QCA::Provider *p, const QString &type) : QCA::HashContext(p, type) { #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0) m_hashObj = Botan::get_hash(hashName.toStdString()); #else m_hashObj = Botan::HashFunction::create(hashName.toStdString()).release(); #endif } ~BotanHashContext() { delete m_hashObj; } Context *clone() const { return new BotanHashContext(*this); } void clear() { m_hashObj->clear(); } void update(const QCA::MemoryRegion &a) { m_hashObj->update( (const Botan::byte*)a.data(), a.size() ); } QCA::MemoryRegion final() { QCA::SecureArray a( m_hashObj->output_length() ); m_hashObj->final( (Botan::byte *)a.data() ); return a; } private: Botan::HashFunction *m_hashObj; }; //----------------------------------------------------------- class BotanHMACContext : public QCA::MACContext { public: BotanHMACContext( const QString &hashName, QCA::Provider *p, const QString &type) : QCA::MACContext(p, type) { #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0) m_hashObj = new Botan::HMAC(Botan::global_state().algorithm_factory().make_hash_function(hashName.toStdString())); #else m_hashObj = new Botan::HMAC(Botan::HashFunction::create_or_throw(hashName.toStdString()).release()); #endif if (0 == m_hashObj) { std::cout << "null context object" << std::endl; } } ~BotanHMACContext() { } void setup(const QCA::SymmetricKey &key) { // this often gets called with an empty key, because that is the default // in the QCA MessageAuthenticationCode constructor. Botan doesn't like // that happening. if (key.size() > 0) { m_hashObj->set_key( (const Botan::byte *)key.data(), key.size() ); } } Context *clone() const { return new BotanHMACContext(*this); } void clear() { m_hashObj->clear(); } QCA::KeyLength keyLength() const { return anyKeyLength(); } void update(const QCA::MemoryRegion &a) { m_hashObj->update( (const Botan::byte*)a.data(), a.size() ); } void final( QCA::MemoryRegion *out) { QCA::SecureArray sa( m_hashObj->output_length(), 0 ); m_hashObj->final( (Botan::byte *)sa.data() ); *out = sa; } protected: Botan::HMAC *m_hashObj; }; //----------------------------------------------------------- class BotanPBKDFContext: public QCA::KDFContext { public: BotanPBKDFContext( const QString &kdfName, QCA::Provider *p, const QString &type) : QCA::KDFContext(p, type) { m_s2k = Botan::get_s2k(kdfName.toStdString()); } ~BotanPBKDFContext() { delete m_s2k; } Context *clone() const { return new BotanPBKDFContext( *this ); } QCA::SymmetricKey makeKey(const QCA::SecureArray &secret, const QCA::InitializationVector &salt, unsigned int keyLength, unsigned int iterationCount) { std::string secretString(secret.data(), secret.size() ); Botan::OctetString key = m_s2k->derive_key(keyLength, secretString, (const Botan::byte*)salt.data(), salt.size(), iterationCount); QCA::SecureArray retval(QByteArray((const char*)key.begin(), key.length())); return QCA::SymmetricKey(retval); } QCA::SymmetricKey makeKey(const QCA::SecureArray &secret, const QCA::InitializationVector &salt, unsigned int keyLength, int msecInterval, unsigned int *iterationCount) { Q_ASSERT(iterationCount != NULL); Botan::OctetString key; QTime timer; std::string secretString(secret.data(), secret.size() ); *iterationCount = 0; timer.start(); while (timer.elapsed() < msecInterval) { key = m_s2k->derive_key(keyLength, secretString, (const Botan::byte*)salt.data(), salt.size(), 1); ++(*iterationCount); } return makeKey(secret, salt, keyLength, *iterationCount); } protected: Botan::S2K* m_s2k; }; +//----------------------------------------------------------- +class BotanHKDFContext: public QCA::HKDFContext +{ +public: + BotanHKDFContext(const QString &hashName, QCA::Provider *p, const QString &type) : QCA::HKDFContext(p, type) + { + Botan::HMAC *hashObj; +#if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0) + hashObj = new Botan::HMAC(Botan::global_state().algorithm_factory().make_hash_function(hashName.toStdString())); +#else + hashObj = new Botan::HMAC(Botan::HashFunction::create_or_throw(hashName.toStdString()).release()); +#endif + m_hkdf = new Botan::HKDF(hashObj); + } + + ~BotanHKDFContext() + { + delete m_hkdf; + } + + Context *clone() const + { + return new BotanHKDFContext( *this ); + } + + QCA::SymmetricKey makeKey(const QCA::SecureArray &secret, const QCA::InitializationVector &salt, + const QCA::InitializationVector &info, unsigned int keyLength) + { + std::string secretString(secret.data(), secret.size()); + Botan::secure_vector key(keyLength); + m_hkdf->kdf(key.data(), keyLength, + reinterpret_cast(secret.data()), secret.size(), + reinterpret_cast(salt.data()), salt.size(), + reinterpret_cast(info.data()), info.size()); + QCA::SecureArray retval(QByteArray::fromRawData(reinterpret_cast(key.data()), key.size())); + return QCA::SymmetricKey(retval); + } + +protected: + Botan::HKDF* m_hkdf; +}; + //----------------------------------------------------------- class BotanCipherContext : public QCA::CipherContext { public: BotanCipherContext( const QString &algo, const QString &mode, const QString &padding, QCA::Provider *p, const QString &type) : QCA::CipherContext(p, type) { m_algoName = algo.toStdString(); m_algoMode = mode.toStdString(); m_algoPadding = padding.toStdString(); } void setup(QCA::Direction dir, const QCA::SymmetricKey &key, const QCA::InitializationVector &iv, const QCA::AuthTag &tag) { Q_UNUSED(tag); try { m_dir = dir; Botan::SymmetricKey keyCopy((Botan::byte*)key.data(), key.size()); if (iv.size() == 0) { if (QCA::Encode == dir) { m_crypter = new Botan::Pipe(Botan::get_cipher(m_algoName+'/'+m_algoMode+'/'+m_algoPadding, keyCopy, Botan::ENCRYPTION)); } else { m_crypter = new Botan::Pipe(Botan::get_cipher(m_algoName+'/'+m_algoMode+'/'+m_algoPadding, keyCopy, Botan::DECRYPTION)); } } else { Botan::InitializationVector ivCopy((Botan::byte*)iv.data(), iv.size()); if (QCA::Encode == dir) { m_crypter = new Botan::Pipe(Botan::get_cipher(m_algoName+'/'+m_algoMode+'/'+m_algoPadding, keyCopy, ivCopy, Botan::ENCRYPTION)); } else { m_crypter = new Botan::Pipe(Botan::get_cipher(m_algoName+'/'+m_algoMode+'/'+m_algoPadding, keyCopy, ivCopy, Botan::DECRYPTION)); } } m_crypter->start_msg(); } catch (Botan::Exception& e) { std::cout << "caught: " << e.what() << std::endl; } } Context *clone() const { return new BotanCipherContext( *this ); } int blockSize() const { #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0) return Botan::block_size_of(m_algoName); #else if(const std::unique_ptr bc = Botan::BlockCipher::create(m_algoName)) return bc->block_size(); throw Botan::Algorithm_Not_Found(m_algoName); #endif } QCA::AuthTag tag() const { // For future implementation return QCA::AuthTag(); } bool update(const QCA::SecureArray &in, QCA::SecureArray *out) { m_crypter->write((Botan::byte*)in.data(), in.size()); QCA::SecureArray result( m_crypter->remaining() ); // Perhaps bytes_read is redundant and can be dropped size_t bytes_read = m_crypter->read((Botan::byte*)result.data(), result.size()); result.resize(bytes_read); *out = result; return true; } bool final(QCA::SecureArray *out) { m_crypter->end_msg(); QCA::SecureArray result( m_crypter->remaining() ); // Perhaps bytes_read is redundant and can be dropped size_t bytes_read = m_crypter->read((Botan::byte*)result.data(), result.size()); result.resize(bytes_read); *out = result; return true; } QCA::KeyLength keyLength() const { #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0) Botan::Algorithm_Factory &af = Botan::global_state().algorithm_factory(); #endif Botan::Key_Length_Specification kls(0); #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0) if(const Botan::BlockCipher *bc = af.prototype_block_cipher(m_algoName)) #else if(const std::unique_ptr bc = Botan::BlockCipher::create(m_algoName)) #endif kls = bc->key_spec(); #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0) else if(const Botan::StreamCipher *sc = af.prototype_stream_cipher(m_algoName)) #else else if(const std::unique_ptr sc = Botan::StreamCipher::create(m_algoName)) #endif kls = sc->key_spec(); #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0) else if(const Botan::MessageAuthenticationCode *mac = af.prototype_mac(m_algoName)) #else else if(const std::unique_ptr mac = Botan::MessageAuthenticationCode::create(m_algoName)) #endif kls = mac->key_spec(); return QCA::KeyLength( kls.minimum_keylength(), kls.maximum_keylength(), kls.keylength_multiple() ); } ~BotanCipherContext() { delete m_crypter; } protected: QCA::Direction m_dir; std::string m_algoName; std::string m_algoMode; std::string m_algoPadding; Botan::Keyed_Filter *m_cipher; Botan::Pipe *m_crypter; }; //========================================================== class botanProvider : public QCA::Provider { public: void init() { #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0) m_init = new Botan::LibraryInitializer; #endif } ~botanProvider() { // We should be cleaning up there, but // this causes the unit tests to segfault // delete m_init; } int qcaVersion() const { return QCA_VERSION; } QString name() const { return "qca-botan"; } QStringList features() const { QStringList list; list += "random"; list += "md2"; list += "md4"; list += "md5"; list += "sha1"; list += "sha256"; list += "sha384"; list += "sha512"; list += "ripemd160"; list += "hmac(md5)"; list += "hmac(sha1)"; // HMAC with SHA2 doesn't appear to work correctly in Botan. // list += "hmac(sha256)"; // list += "hmac(sha384)"; // list += "hmac(sha512)"; list += "hmac(ripemd160)"; list += "pbkdf1(sha1)"; list += "pbkdf1(md2)"; list += "pbkdf2(sha1)"; + list += "hkdf(sha256)"; list += "aes128-ecb"; list += "aes128-cbc"; list += "aes128-cfb"; list += "aes128-ofb"; list += "aes192-ecb"; list += "aes192-cbc"; list += "aes192-cfb"; list += "aes192-ofb"; list += "aes256-ecb"; list += "aes256-cbc"; list += "aes256-cfb"; list += "aes256-ofb"; list += "des-ecb"; list += "des-ecb-pkcs7"; list += "des-cbc"; list += "des-cbc-pkcs7"; list += "des-cfb"; list += "des-ofb"; list += "tripledes-ecb"; list += "blowfish-ecb"; list += "blowfish-cbc"; list += "blowfish-cbc-pkcs7"; list += "blowfish-cfb"; list += "blowfish-ofb"; return list; } Context *createContext(const QString &type) { if ( type == "random" ) return new botanRandomContext( this ); else if ( type == "md2" ) return new BotanHashContext( QString("MD2"), this, type ); else if ( type == "md4" ) return new BotanHashContext( QString("MD4"), this, type ); else if ( type == "md5" ) return new BotanHashContext( QString("MD5"), this, type ); else if ( type == "sha1" ) return new BotanHashContext( QString("SHA-1"), this, type ); else if ( type == "sha256" ) return new BotanHashContext( QString("SHA-256"), this, type ); else if ( type == "sha384" ) return new BotanHashContext( QString("SHA-384"), this, type ); else if ( type == "sha512" ) return new BotanHashContext( QString("SHA-512"), this, type ); else if ( type == "ripemd160" ) return new BotanHashContext( QString("RIPEMD-160"), this, type ); else if ( type == "hmac(md5)" ) return new BotanHMACContext( QString("MD5"), this, type ); else if ( type == "hmac(sha1)" ) return new BotanHMACContext( QString("SHA-1"), this, type ); else if ( type == "hmac(sha256)" ) return new BotanHMACContext( QString("SHA-256"), this, type ); else if ( type == "hmac(sha384)" ) return new BotanHMACContext( QString("SHA-384"), this, type ); else if ( type == "hmac(sha512)" ) return new BotanHMACContext( QString("SHA-512"), this, type ); else if ( type == "hmac(ripemd160)" ) return new BotanHMACContext( QString("RIPEMD-160"), this, type ); else if ( type == "pbkdf1(sha1)" ) return new BotanPBKDFContext( QString("PBKDF1(SHA-1)"), this, type ); else if ( type == "pbkdf1(md2)" ) return new BotanPBKDFContext( QString("PBKDF1(MD2)"), this, type ); else if ( type == "pbkdf2(sha1)" ) return new BotanPBKDFContext( QString("PBKDF2(SHA-1)"), this, type ); + else if ( type == "hkdf(sha256)" ) + return new BotanHKDFContext( QString("SHA-256"), this, type ); else if ( type == "aes128-ecb" ) return new BotanCipherContext( QString("AES-128"), QString("ECB"), QString("NoPadding"), this, type ); else if ( type == "aes128-cbc" ) return new BotanCipherContext( QString("AES-128"), QString("CBC"), QString("NoPadding"), this, type ); else if ( type == "aes128-cfb" ) return new BotanCipherContext( QString("AES-128"), QString("CFB"), QString("NoPadding"), this, type ); else if ( type == "aes128-ofb" ) return new BotanCipherContext( QString("AES-128"), QString("OFB"), QString("NoPadding"), this, type ); else if ( type == "aes192-ecb" ) return new BotanCipherContext( QString("AES-192"), QString("ECB"), QString("NoPadding"), this, type ); else if ( type == "aes192-cbc" ) return new BotanCipherContext( QString("AES-192"), QString("CBC"), QString("NoPadding"), this, type ); else if ( type == "aes192-cfb" ) return new BotanCipherContext( QString("AES-192"), QString("CFB"), QString("NoPadding"), this, type ); else if ( type == "aes192-ofb" ) return new BotanCipherContext( QString("AES-192"), QString("OFB"), QString("NoPadding"), this, type ); else if ( type == "aes256-ecb" ) return new BotanCipherContext( QString("AES-256"), QString("ECB"), QString("NoPadding"), this, type ); else if ( type == "aes256-cbc" ) return new BotanCipherContext( QString("AES-256"), QString("CBC"), QString("NoPadding"), this, type ); else if ( type == "aes256-cfb" ) return new BotanCipherContext( QString("AES-256"), QString("CFB"), QString("NoPadding"), this, type ); else if ( type == "aes256-ofb" ) return new BotanCipherContext( QString("AES-256"), QString("OFB"), QString("NoPadding"), this, type ); else if ( type == "blowfish-ecb" ) return new BotanCipherContext( QString("Blowfish"), QString("ECB"), QString("NoPadding"), this, type ); else if ( type == "blowfish-cbc" ) return new BotanCipherContext( QString("Blowfish"), QString("CBC"), QString("NoPadding"), this, type ); else if ( type == "blowfish-cbc-pkcs7" ) return new BotanCipherContext( QString("Blowfish"), QString("CBC"), QString("PKCS7"), this, type ); else if ( type == "blowfish-cfb" ) return new BotanCipherContext( QString("Blowfish"), QString("CFB"), QString("NoPadding"), this, type ); else if ( type == "blowfish-ofb" ) return new BotanCipherContext( QString("Blowfish"), QString("OFB"), QString("NoPadding"), this, type ); else if ( type == "des-ecb" ) return new BotanCipherContext( QString("DES"), QString("ECB"), QString("NoPadding"), this, type ); else if ( type == "des-ecb-pkcs7" ) return new BotanCipherContext( QString("DES"), QString("ECB"), QString("PKCS7"), this, type ); else if ( type == "des-cbc" ) return new BotanCipherContext( QString("DES"), QString("CBC"), QString("NoPadding"), this, type ); else if ( type == "des-cbc-pkcs7" ) return new BotanCipherContext( QString("DES"), QString("CBC"), QString("PKCS7"), this, type ); else if ( type == "des-cfb" ) return new BotanCipherContext( QString("DES"), QString("CFB"), QString("NoPadding"), this, type ); else if ( type == "des-ofb" ) return new BotanCipherContext( QString("DES"), QString("OFB"), QString("NoPadding"), this, type ); else if ( type == "tripledes-ecb" ) return new BotanCipherContext( QString("TripleDES"), QString("ECB"), QString("NoPadding"), this, type ); else return 0; } private: #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0) Botan::LibraryInitializer *m_init; #endif }; class botanPlugin : public QObject, public QCAPlugin { Q_OBJECT #if QT_VERSION >= 0x050000 Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0") #endif Q_INTERFACES(QCAPlugin) public: virtual QCA::Provider *createProvider() { return new botanProvider; } }; #include "qca-botan.moc" #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(qca_botan, botanPlugin); #endif diff --git a/plugins/qca-ossl/qca-ossl.cpp b/plugins/qca-ossl/qca-ossl.cpp index 3ca9c7c4..6ddad895 100644 --- a/plugins/qca-ossl/qca-ossl.cpp +++ b/plugins/qca-ossl/qca-ossl.cpp @@ -1,7623 +1,7656 @@ /* * Copyright (C) 2004-2007 Justin Karneges * Copyright (C) 2004-2006 Brad Hards * Copyright (C) 2013-2016 Ivan Romanov * Copyright (C) 2017 Fabian Vogt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * */ #include #include #include #include #include #include #include #include +#include #include #include #include #include #include #include #include #include #include #include "ossl110-compat.h" #ifndef OSSL_097 // comment this out if you'd rather use openssl 0.9.6 #define OSSL_097 #endif #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10000000L // OpenSSL 1.0.0 makes a few changes that aren't very C++ friendly... // Among other things, CHECKED_PTR_OF returns a void*, but is used in // contexts requiring STACK pointers. #undef CHECKED_PTR_OF #define CHECKED_PTR_OF(type, p) \ ((_STACK*) (1 ? p : (type*)0)) #endif #if OPENSSL_VERSION_NUMBER >= 0x10100000L #define OSSL_110 #endif // OpenSSL 1.1.0 compatibility macros #ifdef OSSL_110 #define M_ASN1_IA5STRING_new() ASN1_IA5STRING_new() #define RSA_F_RSA_EAY_PRIVATE_DECRYPT RSA_F_RSA_OSSL_PRIVATE_DECRYPT #endif using namespace QCA; namespace opensslQCAPlugin { //---------------------------------------------------------------------------- // Util //---------------------------------------------------------------------------- static SecureArray bio2buf(BIO *b) { SecureArray buf; while(1) { SecureArray block(1024); int ret = BIO_read(b, block.data(), block.size()); if(ret <= 0) break; block.resize(ret); buf.append(block); if(ret != 1024) break; } BIO_free(b); return buf; } static QByteArray bio2ba(BIO *b) { QByteArray buf; while(1) { QByteArray block(1024, 0); int ret = BIO_read(b, block.data(), block.size()); if(ret <= 0) break; block.resize(ret); buf.append(block); if(ret != 1024) break; } BIO_free(b); return buf; } static BigInteger bn2bi(const BIGNUM *n) { SecureArray buf(BN_num_bytes(n) + 1); buf[0] = 0; // positive BN_bn2bin(n, (unsigned char *)buf.data() + 1); return BigInteger(buf); } static BIGNUM *bi2bn(const BigInteger &n) { SecureArray buf = n.toArray(); return BN_bin2bn((const unsigned char *)buf.data(), buf.size(), NULL); } // take lowest bytes of BIGNUM to fit // pad with high byte zeroes to fit static SecureArray bn2fixedbuf(const BIGNUM *n, int size) { SecureArray buf(BN_num_bytes(n)); BN_bn2bin(n, (unsigned char *)buf.data()); SecureArray out(size); memset(out.data(), 0, size); int len = qMin(size, buf.size()); memcpy(out.data() + (size - len), buf.data(), len); return out; } static SecureArray dsasig_der_to_raw(const SecureArray &in) { DSA_SIG *sig = DSA_SIG_new(); const unsigned char *inp = (const unsigned char *)in.data(); d2i_DSA_SIG(&sig, &inp, in.size()); const BIGNUM *bnr, *bns; DSA_SIG_get0(sig, &bnr, &bns); SecureArray part_r = bn2fixedbuf(bnr, 20); SecureArray part_s = bn2fixedbuf(bns, 20); SecureArray result; result.append(part_r); result.append(part_s); DSA_SIG_free(sig); return result; } static SecureArray dsasig_raw_to_der(const SecureArray &in) { if(in.size() != 40) return SecureArray(); DSA_SIG *sig = DSA_SIG_new(); SecureArray part_r(20); BIGNUM *bnr; SecureArray part_s(20); BIGNUM *bns; memcpy(part_r.data(), in.data(), 20); memcpy(part_s.data(), in.data() + 20, 20); bnr = BN_bin2bn((const unsigned char *)part_r.data(), part_r.size(), NULL); bns = BN_bin2bn((const unsigned char *)part_s.data(), part_s.size(), NULL); if(DSA_SIG_set0(sig, bnr, bns) == 0) return SecureArray(); // Not documented what happens in the failure case, free bnr and bns? int len = i2d_DSA_SIG(sig, NULL); SecureArray result(len); unsigned char *p = (unsigned char *)result.data(); i2d_DSA_SIG(sig, &p); DSA_SIG_free(sig); return result; } static int passphrase_cb(char *buf, int size, int rwflag, void *u) { Q_UNUSED(buf); Q_UNUSED(size); Q_UNUSED(rwflag); Q_UNUSED(u); return 0; } /*static bool is_basic_constraint(const ConstraintType &t) { bool basic = false; switch(t.known()) { case DigitalSignature: case NonRepudiation: case KeyEncipherment: case DataEncipherment: case KeyAgreement: case KeyCertificateSign: case CRLSign: case EncipherOnly: case DecipherOnly: basic = true; break; case ServerAuth: case ClientAuth: case CodeSigning: case EmailProtection: case IPSecEndSystem: case IPSecTunnel: case IPSecUser: case TimeStamping: case OCSPSigning: break; } return basic; } static Constraints basic_only(const Constraints &list) { Constraints out; for(int n = 0; n < list.count(); ++n) { if(is_basic_constraint(list[n])) out += list[n]; } return out; } static Constraints ext_only(const Constraints &list) { Constraints out; for(int n = 0; n < list.count(); ++n) { if(!is_basic_constraint(list[n])) out += list[n]; } return out; }*/ // logic from Botan /*static Constraints find_constraints(const PKeyContext &key, const Constraints &orig) { Constraints constraints; if(key.key()->type() == PKey::RSA) constraints += KeyEncipherment; if(key.key()->type() == PKey::DH) constraints += KeyAgreement; if(key.key()->type() == PKey::RSA || key.key()->type() == PKey::DSA) { constraints += DigitalSignature; constraints += NonRepudiation; } Constraints limits = basic_only(orig); Constraints the_rest = ext_only(orig); if(!limits.isEmpty()) { Constraints reduced; for(int n = 0; n < constraints.count(); ++n) { if(limits.contains(constraints[n])) reduced += constraints[n]; } constraints = reduced; } constraints += the_rest; return constraints; }*/ static void try_add_name_item(X509_NAME **name, int nid, const QString &val) { if(val.isEmpty()) return; QByteArray buf = val.toLatin1(); if(!(*name)) *name = X509_NAME_new(); X509_NAME_add_entry_by_NID(*name, nid, MBSTRING_ASC, (unsigned char *)buf.data(), buf.size(), -1, 0); } static X509_NAME *new_cert_name(const CertificateInfo &info) { X509_NAME *name = 0; // FIXME support multiple items of each type try_add_name_item(&name, NID_commonName, info.value(CommonName)); try_add_name_item(&name, NID_countryName, info.value(Country)); try_add_name_item(&name, NID_localityName, info.value(Locality)); try_add_name_item(&name, NID_stateOrProvinceName, info.value(State)); try_add_name_item(&name, NID_organizationName, info.value(Organization)); try_add_name_item(&name, NID_organizationalUnitName, info.value(OrganizationalUnit)); return name; } static void try_get_name_item(X509_NAME *name, int nid, const CertificateInfoType &t, CertificateInfo *info) { int loc; loc = -1; while ((loc = X509_NAME_get_index_by_NID(name, nid, loc)) != -1) { X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, loc); ASN1_STRING *data = X509_NAME_ENTRY_get_data(ne); QByteArray cs((const char *)data->data, data->length); info->insert(t, QString::fromLatin1(cs)); } } static void try_get_name_item_by_oid(X509_NAME *name, const QString &oidText, const CertificateInfoType &t, CertificateInfo *info) { ASN1_OBJECT *oid = OBJ_txt2obj( oidText.toLatin1().data(), 1); // 1 = only accept dotted input if(!oid) return; int loc; loc = -1; while ((loc = X509_NAME_get_index_by_OBJ(name, oid, loc)) != -1) { X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, loc); ASN1_STRING *data = X509_NAME_ENTRY_get_data(ne); QByteArray cs((const char *)data->data, data->length); info->insert(t, QString::fromLatin1(cs)); qDebug() << "oid: " << oidText << ", result: " << cs; } ASN1_OBJECT_free(oid); } static CertificateInfo get_cert_name(X509_NAME *name) { CertificateInfo info; try_get_name_item(name, NID_commonName, CommonName, &info); try_get_name_item(name, NID_countryName, Country, &info); try_get_name_item_by_oid(name, QString("1.3.6.1.4.1.311.60.2.1.3"), IncorporationCountry, &info); try_get_name_item(name, NID_localityName, Locality, &info); try_get_name_item_by_oid(name, QString("1.3.6.1.4.1.311.60.2.1.1"), IncorporationLocality, &info); try_get_name_item(name, NID_stateOrProvinceName, State, &info); try_get_name_item_by_oid(name, QString("1.3.6.1.4.1.311.60.2.1.2"), IncorporationState, &info); try_get_name_item(name, NID_organizationName, Organization, &info); try_get_name_item(name, NID_organizationalUnitName, OrganizationalUnit, &info); // legacy email { CertificateInfo p9_info; try_get_name_item(name, NID_pkcs9_emailAddress, EmailLegacy, &p9_info); QList emails = info.values(Email); QMapIterator it(p9_info); while(it.hasNext()) { it.next(); if(!emails.contains(it.value())) info.insert(Email, it.value()); } } return info; } static X509_EXTENSION *new_subject_key_id(X509 *cert) { X509V3_CTX ctx; X509V3_set_ctx_nodb(&ctx); X509V3_set_ctx(&ctx, NULL, cert, NULL, NULL, 0); X509_EXTENSION *ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_subject_key_identifier, (char *)"hash"); return ex; } static X509_EXTENSION *new_basic_constraints(bool ca, int pathlen) { BASIC_CONSTRAINTS *bs = BASIC_CONSTRAINTS_new(); bs->ca = (ca ? 1: 0); bs->pathlen = ASN1_INTEGER_new(); ASN1_INTEGER_set(bs->pathlen, pathlen); X509_EXTENSION *ex = X509V3_EXT_i2d(NID_basic_constraints, 1, bs); // 1 = critical BASIC_CONSTRAINTS_free(bs); return ex; } static void get_basic_constraints(X509_EXTENSION *ex, bool *ca, int *pathlen) { BASIC_CONSTRAINTS *bs = (BASIC_CONSTRAINTS *)X509V3_EXT_d2i(ex); *ca = (bs->ca ? true: false); if(bs->pathlen) *pathlen = ASN1_INTEGER_get(bs->pathlen); else *pathlen = 0; BASIC_CONSTRAINTS_free(bs); } enum ConstraintBit { Bit_DigitalSignature = 0, Bit_NonRepudiation = 1, Bit_KeyEncipherment = 2, Bit_DataEncipherment = 3, Bit_KeyAgreement = 4, Bit_KeyCertificateSign = 5, Bit_CRLSign = 6, Bit_EncipherOnly = 7, Bit_DecipherOnly = 8 }; static QByteArray ipaddress_string_to_bytes(const QString &) { return QByteArray(4, 0); } static GENERAL_NAME *new_general_name(const CertificateInfoType &t, const QString &val) { GENERAL_NAME *name = 0; switch(t.known()) { case Email: { QByteArray buf = val.toLatin1(); ASN1_IA5STRING *str = M_ASN1_IA5STRING_new(); ASN1_STRING_set((ASN1_STRING *)str, (unsigned char *)buf.data(), buf.size()); name = GENERAL_NAME_new(); name->type = GEN_EMAIL; name->d.rfc822Name = str; break; } case URI: { QByteArray buf = val.toLatin1(); ASN1_IA5STRING *str = M_ASN1_IA5STRING_new(); ASN1_STRING_set((ASN1_STRING *)str, (unsigned char *)buf.data(), buf.size()); name = GENERAL_NAME_new(); name->type = GEN_URI; name->d.uniformResourceIdentifier = str; break; } case DNS: { QByteArray buf = val.toLatin1(); ASN1_IA5STRING *str = M_ASN1_IA5STRING_new(); ASN1_STRING_set((ASN1_STRING *)str, (unsigned char *)buf.data(), buf.size()); name = GENERAL_NAME_new(); name->type = GEN_DNS; name->d.dNSName = str; break; } case IPAddress: { QByteArray buf = ipaddress_string_to_bytes(val); ASN1_OCTET_STRING *str = ASN1_OCTET_STRING_new(); ASN1_STRING_set((ASN1_STRING *)str, (unsigned char *)buf.data(), buf.size()); name = GENERAL_NAME_new(); name->type = GEN_IPADD; name->d.iPAddress = str; break; } case XMPP: { QByteArray buf = val.toUtf8(); ASN1_UTF8STRING *str = ASN1_UTF8STRING_new(); ASN1_STRING_set((ASN1_STRING *)str, (unsigned char *)buf.data(), buf.size()); ASN1_TYPE *at = ASN1_TYPE_new(); at->type = V_ASN1_UTF8STRING; at->value.utf8string = str; OTHERNAME *other = OTHERNAME_new(); other->type_id = OBJ_txt2obj("1.3.6.1.5.5.7.8.5", 1); // 1 = only accept dotted input other->value = at; name = GENERAL_NAME_new(); name->type = GEN_OTHERNAME; name->d.otherName = other; break; } default: break; } return name; } static void try_add_general_name(GENERAL_NAMES **gn, const CertificateInfoType &t, const QString &val) { if(val.isEmpty()) return; GENERAL_NAME *name = new_general_name(t, val); if(name) { if(!(*gn)) *gn = sk_GENERAL_NAME_new_null(); sk_GENERAL_NAME_push(*gn, name); } } static X509_EXTENSION *new_cert_subject_alt_name(const CertificateInfo &info) { GENERAL_NAMES *gn = 0; // FIXME support multiple items of each type try_add_general_name(&gn, Email, info.value(Email)); try_add_general_name(&gn, URI, info.value(URI)); try_add_general_name(&gn, DNS, info.value(DNS)); try_add_general_name(&gn, IPAddress, info.value(IPAddress)); try_add_general_name(&gn, XMPP, info.value(XMPP)); if(!gn) return 0; X509_EXTENSION *ex = X509V3_EXT_i2d(NID_subject_alt_name, 0, gn); sk_GENERAL_NAME_pop_free(gn, GENERAL_NAME_free); return ex; } static GENERAL_NAME *find_next_general_name(GENERAL_NAMES *names, int type, int *pos) { int temp = *pos; GENERAL_NAME *gn = 0; *pos = -1; for(int n = temp; n < sk_GENERAL_NAME_num(names); ++n) { GENERAL_NAME *i = sk_GENERAL_NAME_value(names, n); if(i->type == type) { gn = i; *pos = n; break; } } return gn; } static QByteArray qca_ASN1_STRING_toByteArray(ASN1_STRING *x) { return QByteArray(reinterpret_cast(ASN1_STRING_get0_data(x)), ASN1_STRING_length(x)); } static void try_get_general_name(GENERAL_NAMES *names, const CertificateInfoType &t, CertificateInfo *info) { switch(t.known()) { case Email: { int pos = 0; while (pos != -1) { GENERAL_NAME *gn = find_next_general_name(names, GEN_EMAIL, &pos); if (pos != -1) { QByteArray cs = qca_ASN1_STRING_toByteArray(gn->d.rfc822Name); info->insert(t, QString::fromLatin1(cs)); ++pos; } } break; } case URI: { int pos = 0; while (pos != -1) { GENERAL_NAME *gn = find_next_general_name(names, GEN_URI, &pos); if (pos != -1) { QByteArray cs= qca_ASN1_STRING_toByteArray(gn->d.uniformResourceIdentifier); info->insert(t, QString::fromLatin1(cs)); ++pos; } } break; } case DNS: { int pos = 0; while (pos != -1) { GENERAL_NAME *gn = find_next_general_name(names, GEN_DNS, &pos); if (pos != -1) { QByteArray cs = qca_ASN1_STRING_toByteArray(gn->d.dNSName); info->insert(t, QString::fromLatin1(cs)); ++pos; } } break; } case IPAddress: { int pos = 0; while (pos != -1) { GENERAL_NAME *gn = find_next_general_name(names, GEN_IPADD, &pos); if (pos != -1) { ASN1_OCTET_STRING *str = gn->d.iPAddress; QByteArray buf = qca_ASN1_STRING_toByteArray(str); QString out; // IPv4 (TODO: handle IPv6) if(buf.size() == 4) { out = "0.0.0.0"; } else break; info->insert(t, out); ++pos; } } break; } case XMPP: { int pos = 0; while( pos != -1) { GENERAL_NAME *gn = find_next_general_name(names, GEN_OTHERNAME, &pos); if (pos != -1) { OTHERNAME *other = gn->d.otherName; if(!other) break; ASN1_OBJECT *obj = OBJ_txt2obj("1.3.6.1.5.5.7.8.5", 1); // 1 = only accept dotted input if(OBJ_cmp(other->type_id, obj) != 0) break; ASN1_OBJECT_free(obj); ASN1_TYPE *at = other->value; if(at->type != V_ASN1_UTF8STRING) break; ASN1_UTF8STRING *str = at->value.utf8string; QByteArray buf = qca_ASN1_STRING_toByteArray(str); info->insert(t, QString::fromUtf8(buf)); ++pos; } } break; } default: break; } } static CertificateInfo get_cert_alt_name(X509_EXTENSION *ex) { CertificateInfo info; GENERAL_NAMES *gn = (GENERAL_NAMES *)X509V3_EXT_d2i(ex); try_get_general_name(gn, Email, &info); try_get_general_name(gn, URI, &info); try_get_general_name(gn, DNS, &info); try_get_general_name(gn, IPAddress, &info); try_get_general_name(gn, XMPP, &info); GENERAL_NAMES_free(gn); return info; } static X509_EXTENSION *new_cert_key_usage(const Constraints &constraints) { ASN1_BIT_STRING *keyusage = 0; for(int n = 0; n < constraints.count(); ++n) { int bit = -1; switch(constraints[n].known()) { case DigitalSignature: bit = Bit_DigitalSignature; break; case NonRepudiation: bit = Bit_NonRepudiation; break; case KeyEncipherment: bit = Bit_KeyEncipherment; break; case DataEncipherment: bit = Bit_DataEncipherment; break; case KeyAgreement: bit = Bit_KeyAgreement; break; case KeyCertificateSign: bit = Bit_KeyCertificateSign; break; case CRLSign: bit = Bit_CRLSign; break; case EncipherOnly: bit = Bit_EncipherOnly; break; case DecipherOnly: bit = Bit_DecipherOnly; break; default: break; } if(bit != -1) { if(!keyusage) keyusage = ASN1_BIT_STRING_new(); ASN1_BIT_STRING_set_bit(keyusage, bit, 1); } } if(!keyusage) return 0; X509_EXTENSION *ex = X509V3_EXT_i2d(NID_key_usage, 1, keyusage); // 1 = critical ASN1_BIT_STRING_free(keyusage); return ex; } static Constraints get_cert_key_usage(X509_EXTENSION *ex) { Constraints constraints; int bit_table[9] = { DigitalSignature, NonRepudiation, KeyEncipherment, DataEncipherment, KeyAgreement, KeyCertificateSign, CRLSign, EncipherOnly, DecipherOnly }; ASN1_BIT_STRING *keyusage = (ASN1_BIT_STRING *)X509V3_EXT_d2i(ex); for(int n = 0; n < 9; ++n) { if(ASN1_BIT_STRING_get_bit(keyusage, n)) constraints += ConstraintType((ConstraintTypeKnown)bit_table[n]); } ASN1_BIT_STRING_free(keyusage); return constraints; } static X509_EXTENSION *new_cert_ext_key_usage(const Constraints &constraints) { EXTENDED_KEY_USAGE *extkeyusage = 0; for(int n = 0; n < constraints.count(); ++n) { int nid = -1; // TODO: don't use known/nid, and instead just use OIDs switch(constraints[n].known()) { case ServerAuth: nid = NID_server_auth; break; case ClientAuth: nid = NID_client_auth; break; case CodeSigning: nid = NID_code_sign; break; case EmailProtection: nid = NID_email_protect; break; case IPSecEndSystem: nid = NID_ipsecEndSystem; break; case IPSecTunnel: nid = NID_ipsecTunnel; break; case IPSecUser: nid = NID_ipsecUser; break; case TimeStamping: nid = NID_time_stamp; break; case OCSPSigning: nid = NID_OCSP_sign; break; default: break; } if(nid != -1) { if(!extkeyusage) extkeyusage = sk_ASN1_OBJECT_new_null(); ASN1_OBJECT *obj = OBJ_nid2obj(nid); sk_ASN1_OBJECT_push(extkeyusage, obj); } } if(!extkeyusage) return 0; X509_EXTENSION *ex = X509V3_EXT_i2d(NID_ext_key_usage, 0, extkeyusage); // 0 = not critical sk_ASN1_OBJECT_pop_free(extkeyusage, ASN1_OBJECT_free); return ex; } static Constraints get_cert_ext_key_usage(X509_EXTENSION *ex) { Constraints constraints; EXTENDED_KEY_USAGE *extkeyusage = (EXTENDED_KEY_USAGE *)X509V3_EXT_d2i(ex); for(int n = 0; n < sk_ASN1_OBJECT_num(extkeyusage); ++n) { ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(extkeyusage, n); int nid = OBJ_obj2nid(obj); if(nid == NID_undef) continue; // TODO: don't use known/nid, and instead just use OIDs int t = -1; switch(nid) { case NID_server_auth: t = ServerAuth; break; case NID_client_auth: t = ClientAuth; break; case NID_code_sign: t = CodeSigning; break; case NID_email_protect: t = EmailProtection; break; case NID_ipsecEndSystem: t = IPSecEndSystem; break; case NID_ipsecTunnel: t = IPSecTunnel; break; case NID_ipsecUser: t = IPSecUser; break; case NID_time_stamp: t = TimeStamping; break; case NID_OCSP_sign: t = OCSPSigning; break; }; if(t == -1) continue; constraints.append(ConstraintType((ConstraintTypeKnown)t)); } sk_ASN1_OBJECT_pop_free(extkeyusage, ASN1_OBJECT_free); return constraints; } static X509_EXTENSION *new_cert_policies(const QStringList &policies) { STACK_OF(POLICYINFO) *pols = 0; for(int n = 0; n < policies.count(); ++n) { QByteArray cs = policies[n].toLatin1(); ASN1_OBJECT *obj = OBJ_txt2obj(cs.data(), 1); // 1 = only accept dotted input if(!obj) continue; if(!pols) pols = sk_POLICYINFO_new_null(); POLICYINFO *pol = POLICYINFO_new(); pol->policyid = obj; sk_POLICYINFO_push(pols, pol); } if(!pols) return 0; X509_EXTENSION *ex = X509V3_EXT_i2d(NID_certificate_policies, 0, pols); // 0 = not critical sk_POLICYINFO_pop_free(pols, POLICYINFO_free); return ex; } static QStringList get_cert_policies(X509_EXTENSION *ex) { QStringList out; STACK_OF(POLICYINFO) *pols = (STACK_OF(POLICYINFO) *)X509V3_EXT_d2i(ex); for(int n = 0; n < sk_POLICYINFO_num(pols); ++n) { POLICYINFO *pol = sk_POLICYINFO_value(pols, n); QByteArray buf(128, 0); OBJ_obj2txt((char *)buf.data(), buf.size(), pol->policyid, 1); // 1 = only accept dotted input out += QString::fromLatin1(buf); } sk_POLICYINFO_pop_free(pols, POLICYINFO_free); return out; } static QByteArray get_cert_subject_key_id(X509_EXTENSION *ex) { ASN1_OCTET_STRING *skid = (ASN1_OCTET_STRING *)X509V3_EXT_d2i(ex); QByteArray out = qca_ASN1_STRING_toByteArray(skid); ASN1_OCTET_STRING_free(skid); return out; } // If you get any more crashes in this code, please provide a copy // of the cert to bradh AT frogmouth.net static QByteArray get_cert_issuer_key_id(X509_EXTENSION *ex) { AUTHORITY_KEYID *akid = (AUTHORITY_KEYID *)X509V3_EXT_d2i(ex); QByteArray out; if (akid->keyid) out = qca_ASN1_STRING_toByteArray(akid->keyid); AUTHORITY_KEYID_free(akid); return out; } static Validity convert_verify_error(int err) { // TODO: ErrorExpiredCA Validity rc; switch(err) { case X509_V_ERR_CERT_REJECTED: rc = ErrorRejected; break; case X509_V_ERR_CERT_UNTRUSTED: rc = ErrorUntrusted; break; case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: case X509_V_ERR_CERT_SIGNATURE_FAILURE: case X509_V_ERR_CRL_SIGNATURE_FAILURE: case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: rc = ErrorSignatureFailed; break; case X509_V_ERR_INVALID_CA: case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: rc = ErrorInvalidCA; break; case X509_V_ERR_INVALID_PURPOSE: // note: not used by store verify rc = ErrorInvalidPurpose; break; case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: rc = ErrorSelfSigned; break; case X509_V_ERR_CERT_REVOKED: rc = ErrorRevoked; break; case X509_V_ERR_PATH_LENGTH_EXCEEDED: rc = ErrorPathLengthExceeded; break; case X509_V_ERR_CERT_NOT_YET_VALID: case X509_V_ERR_CERT_HAS_EXPIRED: case X509_V_ERR_CRL_NOT_YET_VALID: case X509_V_ERR_CRL_HAS_EXPIRED: case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: rc = ErrorExpired; break; case X509_V_ERR_APPLICATION_VERIFICATION: case X509_V_ERR_OUT_OF_MEM: case X509_V_ERR_UNABLE_TO_GET_CRL: case X509_V_ERR_CERT_CHAIN_TOO_LONG: default: rc = ErrorValidityUnknown; break; } return rc; } EVP_PKEY *qca_d2i_PKCS8PrivateKey(const SecureArray &in, EVP_PKEY **x, pem_password_cb *cb, void *u) { PKCS8_PRIV_KEY_INFO *p8inf; // first try unencrypted form BIO *bi = BIO_new(BIO_s_mem()); BIO_write(bi, in.data(), in.size()); p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(bi, NULL); BIO_free(bi); if(!p8inf) { X509_SIG *p8; // now try encrypted form bi = BIO_new(BIO_s_mem()); BIO_write(bi, in.data(), in.size()); p8 = d2i_PKCS8_bio(bi, NULL); BIO_free(bi); if(!p8) return NULL; // get passphrase char psbuf[PEM_BUFSIZE]; int klen; if(cb) klen = cb(psbuf, PEM_BUFSIZE, 0, u); else klen = PEM_def_callback(psbuf, PEM_BUFSIZE, 0, u); if(klen <= 0) { PEMerr(PEM_F_D2I_PKCS8PRIVATEKEY_BIO, PEM_R_BAD_PASSWORD_READ); X509_SIG_free(p8); return NULL; } // decrypt it p8inf = PKCS8_decrypt(p8, psbuf, klen); X509_SIG_free(p8); if(!p8inf) return NULL; } EVP_PKEY *ret = EVP_PKCS82PKEY(p8inf); PKCS8_PRIV_KEY_INFO_free(p8inf); if(!ret) return NULL; if(x) { if(*x) EVP_PKEY_free(*x); *x = ret; } return ret; } class opensslHashContext : public HashContext { public: opensslHashContext(const EVP_MD *algorithm, Provider *p, const QString &type) : HashContext(p, type) { m_algorithm = algorithm; m_context = EVP_MD_CTX_new(); EVP_DigestInit( m_context, m_algorithm ); } opensslHashContext(const opensslHashContext &other) : HashContext(other) { m_algorithm = other.m_algorithm; m_context = EVP_MD_CTX_new(); EVP_MD_CTX_copy_ex(m_context, other.m_context); } ~opensslHashContext() { EVP_MD_CTX_free(m_context); } void clear() { EVP_MD_CTX_free(m_context); m_context = EVP_MD_CTX_new(); EVP_DigestInit( m_context, m_algorithm ); } void update(const MemoryRegion &a) { EVP_DigestUpdate( m_context, (unsigned char*)a.data(), a.size() ); } MemoryRegion final() { SecureArray a( EVP_MD_size( m_algorithm ) ); EVP_DigestFinal( m_context, (unsigned char*)a.data(), 0 ); return a; } Provider::Context *clone() const { return new opensslHashContext(*this); } protected: const EVP_MD *m_algorithm; EVP_MD_CTX *m_context; }; class opensslPbkdf1Context : public KDFContext { public: opensslPbkdf1Context(const EVP_MD *algorithm, Provider *p, const QString &type) : KDFContext(p, type) { m_algorithm = algorithm; m_context = EVP_MD_CTX_new(); EVP_DigestInit( m_context, m_algorithm ); } opensslPbkdf1Context(const opensslPbkdf1Context &other) : KDFContext(other) { m_algorithm = other.m_algorithm; m_context = EVP_MD_CTX_new(); EVP_MD_CTX_copy(m_context, other.m_context); } ~opensslPbkdf1Context() { EVP_MD_CTX_free(m_context); } Provider::Context *clone() const { return new opensslPbkdf1Context( *this ); } SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, unsigned int iterationCount) { /* from RFC2898: Steps: 1. If dkLen > 16 for MD2 and MD5, or dkLen > 20 for SHA-1, output "derived key too long" and stop. */ if ( keyLength > (unsigned int)EVP_MD_size( m_algorithm ) ) { std::cout << "derived key too long" << std::endl; return SymmetricKey(); } /* 2. Apply the underlying hash function Hash for c iterations to the concatenation of the password P and the salt S, then extract the first dkLen octets to produce a derived key DK: T_1 = Hash (P || S) , T_2 = Hash (T_1) , ... T_c = Hash (T_{c-1}) , DK = Tc<0..dkLen-1> */ // calculate T_1 EVP_DigestUpdate( m_context, (unsigned char*)secret.data(), secret.size() ); EVP_DigestUpdate( m_context, (unsigned char*)salt.data(), salt.size() ); SecureArray a( EVP_MD_size( m_algorithm ) ); EVP_DigestFinal( m_context, (unsigned char*)a.data(), 0 ); // calculate T_2 up to T_c for ( unsigned int i = 2; i <= iterationCount; ++i ) { EVP_DigestInit( m_context, m_algorithm ); EVP_DigestUpdate( m_context, (unsigned char*)a.data(), a.size() ); EVP_DigestFinal( m_context, (unsigned char*)a.data(), 0 ); } // shrink a to become DK, of the required length a.resize(keyLength); /* 3. Output the derived key DK. */ return a; } SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, int msecInterval, unsigned int *iterationCount) { Q_ASSERT(iterationCount != NULL); QTime timer; /* from RFC2898: Steps: 1. If dkLen > 16 for MD2 and MD5, or dkLen > 20 for SHA-1, output "derived key too long" and stop. */ if ( keyLength > (unsigned int)EVP_MD_size( m_algorithm ) ) { std::cout << "derived key too long" << std::endl; return SymmetricKey(); } /* 2. Apply the underlying hash function Hash for M milliseconds to the concatenation of the password P and the salt S, incrementing c, then extract the first dkLen octets to produce a derived key DK: time from M to 0 T_1 = Hash (P || S) , T_2 = Hash (T_1) , ... T_c = Hash (T_{c-1}) , when time = 0: stop, DK = Tc<0..dkLen-1> */ // calculate T_1 EVP_DigestUpdate( m_context, (unsigned char*)secret.data(), secret.size() ); EVP_DigestUpdate( m_context, (unsigned char*)salt.data(), salt.size() ); SecureArray a( EVP_MD_size( m_algorithm ) ); EVP_DigestFinal( m_context, (unsigned char*)a.data(), 0 ); // calculate T_2 up to T_c *iterationCount = 2 - 1; // <- Have to remove 1, unless it computes one timer.start(); // ^ time more than the base function // ^ with the same iterationCount while (timer.elapsed() < msecInterval) { EVP_DigestInit( m_context, m_algorithm ); EVP_DigestUpdate( m_context, (unsigned char*)a.data(), a.size() ); EVP_DigestFinal( m_context, (unsigned char*)a.data(), 0 ); ++(*iterationCount); } // shrink a to become DK, of the required length a.resize(keyLength); /* 3. Output the derived key DK. */ return a; } protected: const EVP_MD *m_algorithm; EVP_MD_CTX *m_context; }; class opensslPbkdf2Context : public KDFContext { public: opensslPbkdf2Context(Provider *p, const QString &type) : KDFContext(p, type) { } Provider::Context *clone() const { return new opensslPbkdf2Context( *this ); } SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, unsigned int iterationCount) { SecureArray out(keyLength); PKCS5_PBKDF2_HMAC_SHA1( (char*)secret.data(), secret.size(), (unsigned char*)salt.data(), salt.size(), iterationCount, keyLength, (unsigned char*)out.data() ); return out; } SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, int msecInterval, unsigned int *iterationCount) { Q_ASSERT(iterationCount != NULL); QTime timer; SecureArray out(keyLength); *iterationCount = 0; timer.start(); // PBKDF2 needs an iterationCount itself, unless PBKDF1. // So we need to calculate first the number of iterations for // That time interval, then feed the iterationCounts to PBKDF2 while (timer.elapsed() < msecInterval) { PKCS5_PBKDF2_HMAC_SHA1((char*)secret.data(), secret.size(), (unsigned char*)salt.data(), salt.size(), 1, keyLength, (unsigned char*)out.data()); ++(*iterationCount); } // Now we can directely call makeKey base function, // as we now have the iterationCount out = makeKey(secret, salt, keyLength, *iterationCount); return out; } protected: }; +class opensslHkdfContext : public HKDFContext +{ +public: + opensslHkdfContext(Provider *p, const QString &type) : HKDFContext(p, type) + { + } + + Provider::Context *clone() const + { + return new opensslHkdfContext( *this ); + } + + SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, + const InitializationVector &info, unsigned int keyLength) + { + SecureArray out(keyLength); + EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL); + EVP_PKEY_derive_init(pctx); + EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256()); + EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt.data(), int(salt.size())); + EVP_PKEY_CTX_set1_hkdf_key(pctx, secret.data(), int(secret.size())); + EVP_PKEY_CTX_add1_hkdf_info(pctx, info.data(), int(info.size())); + size_t outlen = out.size(); + EVP_PKEY_derive(pctx, reinterpret_cast(out.data()), &outlen); + EVP_PKEY_CTX_free(pctx); + return out; + } +}; + class opensslHMACContext : public MACContext { public: opensslHMACContext(const EVP_MD *algorithm, Provider *p, const QString &type) : MACContext(p, type) { m_algorithm = algorithm; m_context = HMAC_CTX_new(); #ifndef OSSL_110 HMAC_CTX_init( m_context ); #endif } opensslHMACContext(const opensslHMACContext &other) : MACContext(other) { m_algorithm = other.m_algorithm; m_context = HMAC_CTX_new(); HMAC_CTX_copy(m_context, other.m_context); } ~opensslHMACContext() { HMAC_CTX_free(m_context); } void setup(const SymmetricKey &key) { HMAC_Init_ex( m_context, key.data(), key.size(), m_algorithm, 0 ); } KeyLength keyLength() const { return anyKeyLength(); } void update(const MemoryRegion &a) { HMAC_Update( m_context, (unsigned char *)a.data(), a.size() ); } void final(MemoryRegion *out) { SecureArray sa( EVP_MD_size( m_algorithm ), 0 ); HMAC_Final(m_context, (unsigned char *)sa.data(), 0 ); #ifdef OSSL_110 HMAC_CTX_reset(m_context); #else HMAC_CTX_cleanup(m_context); #endif *out = sa; } Provider::Context *clone() const { return new opensslHMACContext(*this); } protected: HMAC_CTX *m_context; const EVP_MD *m_algorithm; }; //---------------------------------------------------------------------------- // EVPKey //---------------------------------------------------------------------------- // note: this class squelches processing errors, since QCA doesn't care about them class EVPKey { public: enum State { Idle, SignActive, SignError, VerifyActive, VerifyError }; EVP_PKEY *pkey; EVP_MD_CTX *mdctx; State state; bool raw_type; SecureArray raw; EVPKey() { pkey = 0; raw_type = false; state = Idle; mdctx = EVP_MD_CTX_new(); } EVPKey(const EVPKey &from) { pkey = from.pkey; EVP_PKEY_up_ref(pkey); raw_type = false; state = Idle; mdctx = EVP_MD_CTX_new(); EVP_MD_CTX_copy(mdctx, from.mdctx); } ~EVPKey() { reset(); EVP_MD_CTX_free(mdctx); } void reset() { if(pkey) EVP_PKEY_free(pkey); pkey = 0; raw.clear (); raw_type = false; } void startSign(const EVP_MD *type) { state = SignActive; if(!type) { raw_type = true; raw.clear (); } else { raw_type = false; EVP_MD_CTX_init(mdctx); if(!EVP_SignInit_ex(mdctx, type, NULL)) state = SignError; } } void startVerify(const EVP_MD *type) { state = VerifyActive; if(!type) { raw_type = true; raw.clear (); } else { raw_type = false; EVP_MD_CTX_init(mdctx); if(!EVP_VerifyInit_ex(mdctx, type, NULL)) state = VerifyError; } } void update(const MemoryRegion &in) { if(state == SignActive) { if (raw_type) raw += in; else if(!EVP_SignUpdate(mdctx, in.data(), (unsigned int)in.size())) state = SignError; } else if(state == VerifyActive) { if (raw_type) raw += in; else if(!EVP_VerifyUpdate(mdctx, in.data(), (unsigned int)in.size())) state = VerifyError; } } SecureArray endSign() { if(state == SignActive) { SecureArray out(EVP_PKEY_size(pkey)); unsigned int len = out.size(); if (raw_type) { int type = EVP_PKEY_id(pkey); if (type == EVP_PKEY_RSA) { RSA *rsa = EVP_PKEY_get0_RSA(pkey); if(RSA_private_encrypt (raw.size(), (unsigned char *)raw.data(), (unsigned char *)out.data(), rsa, RSA_PKCS1_PADDING) == -1) { state = SignError; return SecureArray (); } } else if (type == EVP_PKEY_DSA) { state = SignError; return SecureArray (); } else { state = SignError; return SecureArray (); } } else { if(!EVP_SignFinal(mdctx, (unsigned char *)out.data(), &len, pkey)) { state = SignError; return SecureArray(); } } out.resize(len); state = Idle; return out; } else return SecureArray(); } bool endVerify(const SecureArray &sig) { if(state == VerifyActive) { if (raw_type) { SecureArray out(EVP_PKEY_size(pkey)); int len = 0; int type = EVP_PKEY_id(pkey); if (type == EVP_PKEY_RSA) { RSA *rsa = EVP_PKEY_get0_RSA(pkey); if((len = RSA_public_decrypt (sig.size(), (unsigned char *)sig.data(), (unsigned char *)out.data (), rsa, RSA_PKCS1_PADDING)) == -1) { state = VerifyError; return false; } } else if (type == EVP_PKEY_DSA) { state = VerifyError; return false; } else { state = VerifyError; return false; } out.resize (len); if (out != raw) { state = VerifyError; return false; } } else { if(EVP_VerifyFinal(mdctx, (unsigned char *)sig.data(), (unsigned int)sig.size(), pkey) != 1) { state = VerifyError; return false; } } state = Idle; return true; } else return false; } }; //---------------------------------------------------------------------------- // MyDLGroup //---------------------------------------------------------------------------- // IETF primes from Botan const char* IETF_1024_PRIME = "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381" "FFFFFFFF FFFFFFFF"; const char* IETF_2048_PRIME = "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" "15728E5A 8AACAA68 FFFFFFFF FFFFFFFF"; const char* IETF_4096_PRIME = "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" "15728E5A 8AAAC42D AD33170D 04507A33 A85521AB DF1CBA64" "ECFB8504 58DBEF0A 8AEA7157 5D060C7D B3970F85 A6E1E4C7" "ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B" "F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C" "BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31" "43DB5BFC E0FD108E 4B82D120 A9210801 1A723C12 A787E6D7" "88719A10 BDBA5B26 99C32718 6AF4E23C 1A946834 B6150BDA" "2583E9CA 2AD44CE8 DBBBC2DB 04DE8EF9 2E8EFC14 1FBECAA6" "287C5947 4E6BC05D 99B2964F A090C3A2 233BA186 515BE7ED" "1F612970 CEE2D7AF B81BDD76 2170481C D0069127 D5B05AA9" "93B4EA98 8D8FDDC1 86FFB7DC 90A6C08F 4DF435C9 34063199" "FFFFFFFF FFFFFFFF"; // JCE seeds from Botan const char* JCE_512_SEED = "B869C82B 35D70E1B 1FF91B28 E37A62EC DC34409B"; const int JCE_512_COUNTER = 123; const char* JCE_768_SEED = "77D0F8C4 DAD15EB8 C4F2F8D6 726CEFD9 6D5BB399"; const int JCE_768_COUNTER = 263; const char* JCE_1024_SEED = "8D515589 4229D5E6 89EE01E6 018A237E 2CAE64CD"; const int JCE_1024_COUNTER = 92; static QByteArray dehex(const QString &hex) { QString str; for(int n = 0; n < hex.length(); ++n) { if(hex[n] != ' ') str += hex[n]; } return hexToArray(str); } static BigInteger decode(const QString &prime) { QByteArray a(1, 0); // 1 byte of zero padding a.append(dehex(prime)); return BigInteger(SecureArray(a)); } #ifndef OPENSSL_FIPS static QByteArray decode_seed(const QString &hex_seed) { return dehex(hex_seed); } #endif class DLParams { public: BigInteger p, q, g; }; #ifndef OPENSSL_FIPS namespace { struct DsaDeleter { static inline void cleanup(void *pointer) { if (pointer) DSA_free((DSA *)pointer); } }; } // end of anonymous namespace static bool make_dlgroup(const QByteArray &seed, int bits, int counter, DLParams *params) { int ret_counter; QScopedPointer dsa(DSA_new()); if(!dsa) return false; if (DSA_generate_parameters_ex(dsa.data(), bits, (const unsigned char *)seed.data(), seed.size(), &ret_counter, NULL, NULL) != 1) return false; if(ret_counter != counter) return false; const BIGNUM *bnp, *bnq, *bng; DSA_get0_pqg(dsa.data(), &bnp, &bnq, &bng); params->p = bn2bi(bnp); params->q = bn2bi(bnq); params->g = bn2bi(bng); return true; } #endif static bool get_dlgroup(const BigInteger &p, const BigInteger &g, DLParams *params) { params->p = p; params->q = BigInteger(0); params->g = g; return true; } class DLGroupMaker : public QThread { Q_OBJECT public: DLGroupSet set; bool ok; DLParams params; DLGroupMaker(DLGroupSet _set) { set = _set; } ~DLGroupMaker() { wait(); } virtual void run() { switch (set) { #ifndef OPENSSL_FIPS case DSA_512: ok = make_dlgroup(decode_seed(JCE_512_SEED), 512, JCE_512_COUNTER, ¶ms); break; case DSA_768: ok = make_dlgroup(decode_seed(JCE_768_SEED), 768, JCE_768_COUNTER, ¶ms); break; case DSA_1024: ok = make_dlgroup(decode_seed(JCE_1024_SEED), 1024, JCE_1024_COUNTER, ¶ms); break; #endif case IETF_1024: ok = get_dlgroup(decode(IETF_1024_PRIME), 2, ¶ms); break; case IETF_2048: ok = get_dlgroup(decode(IETF_2048_PRIME), 2, ¶ms); break; case IETF_4096: ok = get_dlgroup(decode(IETF_4096_PRIME), 2, ¶ms); break; default: ok = false; break; } } }; class MyDLGroup : public DLGroupContext { Q_OBJECT public: DLGroupMaker *gm; bool wasBlocking; DLParams params; bool empty; MyDLGroup(Provider *p) : DLGroupContext(p) { gm = 0; empty = true; } MyDLGroup(const MyDLGroup &from) : DLGroupContext(from.provider()) { gm = 0; empty = true; } ~MyDLGroup() { delete gm; } virtual Provider::Context *clone() const { return new MyDLGroup(*this); } virtual QList supportedGroupSets() const { QList list; // DSA_* was removed in FIPS specification // https://bugzilla.redhat.com/show_bug.cgi?id=1144655 #ifndef OPENSSL_FIPS list += DSA_512; list += DSA_768; list += DSA_1024; #endif list += IETF_1024; list += IETF_2048; list += IETF_4096; return list; } virtual bool isNull() const { return empty; } virtual void fetchGroup(DLGroupSet set, bool block) { params = DLParams(); empty = true; gm = new DLGroupMaker(set); wasBlocking = block; if(block) { gm->run(); gm_finished(); } else { connect(gm, SIGNAL(finished()), SLOT(gm_finished())); gm->start(); } } virtual void getResult(BigInteger *p, BigInteger *q, BigInteger *g) const { *p = params.p; *q = params.q; *g = params.g; } private slots: void gm_finished() { bool ok = gm->ok; if(ok) { params = gm->params; empty = false; } if(wasBlocking) delete gm; else gm->deleteLater(); gm = 0; if(!wasBlocking) emit finished(); } }; //---------------------------------------------------------------------------- // RSAKey //---------------------------------------------------------------------------- namespace { struct RsaDeleter { static inline void cleanup(void *pointer) { if (pointer) RSA_free((RSA *)pointer); } }; struct BnDeleter { static inline void cleanup(void *pointer) { if (pointer) BN_free((BIGNUM *)pointer); } }; } // end of anonymous namespace class RSAKeyMaker : public QThread { Q_OBJECT public: RSA *result; int bits, exp; RSAKeyMaker(int _bits, int _exp, QObject *parent = 0) : QThread(parent), result(0), bits(_bits), exp(_exp) { } ~RSAKeyMaker() { wait(); if(result) RSA_free(result); } virtual void run() { QScopedPointer rsa(RSA_new()); if(!rsa) return; QScopedPointer e(BN_new()); if(!e) return; BN_clear(e.data()); if (BN_set_word(e.data(), exp) != 1) return; if (RSA_generate_key_ex(rsa.data(), bits, e.data(), NULL) == 0) return; result = rsa.take(); } RSA *takeResult() { RSA *rsa = result; result = 0; return rsa; } }; class RSAKey : public RSAContext { Q_OBJECT public: EVPKey evp; RSAKeyMaker *keymaker; bool wasBlocking; bool sec; RSAKey(Provider *p) : RSAContext(p) { keymaker = 0; sec = false; } RSAKey(const RSAKey &from) : RSAContext(from.provider()), evp(from.evp) { keymaker = 0; sec = from.sec; } ~RSAKey() { delete keymaker; } virtual Provider::Context *clone() const { return new RSAKey(*this); } virtual bool isNull() const { return (evp.pkey ? false: true); } virtual PKey::Type type() const { return PKey::RSA; } virtual bool isPrivate() const { return sec; } virtual bool canExport() const { return true; } virtual void convertToPublic() { if(!sec) return; // extract the public key into DER format RSA *rsa_pkey = EVP_PKEY_get0_RSA(evp.pkey); int len = i2d_RSAPublicKey(rsa_pkey, NULL); SecureArray result(len); unsigned char *p = (unsigned char *)result.data(); i2d_RSAPublicKey(rsa_pkey, &p); p = (unsigned char *)result.data(); // put the DER public key back into openssl evp.reset(); RSA *rsa; #ifdef OSSL_097 rsa = d2i_RSAPublicKey(NULL, (const unsigned char **)&p, result.size()); #else rsa = d2i_RSAPublicKey(NULL, (unsigned char **)&p, result.size()); #endif evp.pkey = EVP_PKEY_new(); EVP_PKEY_assign_RSA(evp.pkey, rsa); sec = false; } virtual int bits() const { return EVP_PKEY_bits(evp.pkey); } virtual int maximumEncryptSize(EncryptionAlgorithm alg) const { RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey); int size = 0; switch(alg) { case EME_PKCS1v15: size = RSA_size(rsa) - 11 - 1; break; case EME_PKCS1_OAEP: size = RSA_size(rsa) - 41 - 1; break; case EME_PKCS1v15_SSL: size = RSA_size(rsa) - 11 - 1; break; case EME_NO_PADDING: size = RSA_size(rsa) - 1; break; } return size; } virtual SecureArray encrypt(const SecureArray &in, EncryptionAlgorithm alg) { RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey); SecureArray buf = in; int max = maximumEncryptSize(alg); if(buf.size() > max) buf.resize(max); SecureArray result(RSA_size(rsa)); int pad; switch(alg) { case EME_PKCS1v15: pad = RSA_PKCS1_PADDING; break; case EME_PKCS1_OAEP: pad = RSA_PKCS1_OAEP_PADDING; break; case EME_PKCS1v15_SSL: pad = RSA_SSLV23_PADDING; break; case EME_NO_PADDING: pad = RSA_NO_PADDING; break; default: return SecureArray(); break; } int ret; if (isPrivate()) ret = RSA_private_encrypt(buf.size(), (unsigned char *)buf.data(), (unsigned char *)result.data(), rsa, pad); else ret = RSA_public_encrypt(buf.size(), (unsigned char *)buf.data(), (unsigned char *)result.data(), rsa, pad); if(ret < 0) return SecureArray(); result.resize(ret); return result; } virtual bool decrypt(const SecureArray &in, SecureArray *out, EncryptionAlgorithm alg) { RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey); SecureArray result(RSA_size(rsa)); int pad; switch(alg) { case EME_PKCS1v15: pad = RSA_PKCS1_PADDING; break; case EME_PKCS1_OAEP: pad = RSA_PKCS1_OAEP_PADDING; break; case EME_PKCS1v15_SSL: pad = RSA_SSLV23_PADDING; break; case EME_NO_PADDING: pad = RSA_NO_PADDING; break; default: return false; break; } int ret; if (isPrivate()) ret = RSA_private_decrypt(in.size(), (unsigned char *)in.data(), (unsigned char *)result.data(), rsa, pad); else ret = RSA_public_decrypt(in.size(), (unsigned char *)in.data(), (unsigned char *)result.data(), rsa, pad); if(ret < 0) return false; result.resize(ret); *out = result; return true; } virtual void startSign(SignatureAlgorithm alg, SignatureFormat) { const EVP_MD *md = 0; if(alg == EMSA3_SHA1) md = EVP_sha1(); else if(alg == EMSA3_MD5) md = EVP_md5(); #ifdef HAVE_OPENSSL_MD2 else if(alg == EMSA3_MD2) md = EVP_md2(); #endif else if(alg == EMSA3_RIPEMD160) md = EVP_ripemd160(); else if(alg == EMSA3_SHA224) md = EVP_sha224(); else if(alg == EMSA3_SHA256) md = EVP_sha256(); else if(alg == EMSA3_SHA384) md = EVP_sha384(); else if(alg == EMSA3_SHA512) md = EVP_sha512(); else if(alg == EMSA3_Raw) { // md = 0 } evp.startSign(md); } virtual void startVerify(SignatureAlgorithm alg, SignatureFormat) { const EVP_MD *md = 0; if(alg == EMSA3_SHA1) md = EVP_sha1(); else if(alg == EMSA3_MD5) md = EVP_md5(); #ifdef HAVE_OPENSSL_MD2 else if(alg == EMSA3_MD2) md = EVP_md2(); #endif else if(alg == EMSA3_RIPEMD160) md = EVP_ripemd160(); else if(alg == EMSA3_SHA224) md = EVP_sha224(); else if(alg == EMSA3_SHA256) md = EVP_sha256(); else if(alg == EMSA3_SHA384) md = EVP_sha384(); else if(alg == EMSA3_SHA512) md = EVP_sha512(); else if(alg == EMSA3_Raw) { // md = 0 } evp.startVerify(md); } virtual void update(const MemoryRegion &in) { evp.update(in); } virtual QByteArray endSign() { return evp.endSign().toByteArray(); } virtual bool endVerify(const QByteArray &sig) { return evp.endVerify(sig); } virtual void createPrivate(int bits, int exp, bool block) { evp.reset(); keymaker = new RSAKeyMaker(bits, exp, !block ? this : 0); wasBlocking = block; if(block) { keymaker->run(); km_finished(); } else { connect(keymaker, SIGNAL(finished()), SLOT(km_finished())); keymaker->start(); } } virtual void createPrivate(const BigInteger &n, const BigInteger &e, const BigInteger &p, const BigInteger &q, const BigInteger &d) { evp.reset(); RSA *rsa = RSA_new(); if(RSA_set0_key(rsa, bi2bn(n), bi2bn(e), bi2bn(d)) == 0 || RSA_set0_factors(rsa, bi2bn(p), bi2bn(q)) == 0) { // Free BIGNUMS? RSA_free(rsa); return; } // When private key has no Public Exponent (e) or Private Exponent (d) // need to disable blinding. Otherwise decryption will be broken. // http://www.mail-archive.com/openssl-users@openssl.org/msg63530.html if(e == BigInteger(0) || d == BigInteger(0)) RSA_blinding_off(rsa); evp.pkey = EVP_PKEY_new(); EVP_PKEY_assign_RSA(evp.pkey, rsa); sec = true; } virtual void createPublic(const BigInteger &n, const BigInteger &e) { evp.reset(); RSA *rsa = RSA_new(); if(RSA_set0_key(rsa, bi2bn(n), bi2bn(e), NULL) == 0) { RSA_free(rsa); return; } evp.pkey = EVP_PKEY_new(); EVP_PKEY_assign_RSA(evp.pkey, rsa); sec = false; } virtual BigInteger n() const { RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey); const BIGNUM *bnn; RSA_get0_key(rsa, &bnn, NULL, NULL); return bn2bi(bnn); } virtual BigInteger e() const { RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey); const BIGNUM *bne; RSA_get0_key(rsa, NULL, &bne, NULL); return bn2bi(bne); } virtual BigInteger p() const { RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey); const BIGNUM *bnp; RSA_get0_factors(rsa, &bnp, NULL); return bn2bi(bnp); } virtual BigInteger q() const { RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey); const BIGNUM *bnq; RSA_get0_factors(rsa, NULL, &bnq); return bn2bi(bnq); } virtual BigInteger d() const { RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey); const BIGNUM *bnd; RSA_get0_key(rsa, NULL, NULL, &bnd); return bn2bi(bnd); } private slots: void km_finished() { RSA *rsa = keymaker->takeResult(); if(wasBlocking) delete keymaker; else keymaker->deleteLater(); keymaker = 0; if(rsa) { evp.pkey = EVP_PKEY_new(); EVP_PKEY_assign_RSA(evp.pkey, rsa); sec = true; } if(!wasBlocking) emit finished(); } }; //---------------------------------------------------------------------------- // DSAKey //---------------------------------------------------------------------------- class DSAKeyMaker : public QThread { Q_OBJECT public: DLGroup domain; DSA *result; DSAKeyMaker(const DLGroup &_domain, QObject *parent = 0) : QThread(parent), domain(_domain), result(0) { } ~DSAKeyMaker() { wait(); if(result) DSA_free(result); } virtual void run() { DSA *dsa = DSA_new(); BIGNUM *pne = bi2bn(domain.p()), *qne = bi2bn(domain.q()), *gne = bi2bn(domain.g()); if(!DSA_set0_pqg(dsa, pne, qne, gne) || !DSA_generate_key(dsa)) { DSA_free(dsa); return; } result = dsa; } DSA *takeResult() { DSA *dsa = result; result = 0; return dsa; } }; // note: DSA doesn't use SignatureAlgorithm, since EMSA1 is always assumed class DSAKey : public DSAContext { Q_OBJECT public: EVPKey evp; DSAKeyMaker *keymaker; bool wasBlocking; bool transformsig; bool sec; DSAKey(Provider *p) : DSAContext(p) { keymaker = 0; sec = false; } DSAKey(const DSAKey &from) : DSAContext(from.provider()), evp(from.evp) { keymaker = 0; sec = from.sec; } ~DSAKey() { delete keymaker; } virtual Provider::Context *clone() const { return new DSAKey(*this); } virtual bool isNull() const { return (evp.pkey ? false: true); } virtual PKey::Type type() const { return PKey::DSA; } virtual bool isPrivate() const { return sec; } virtual bool canExport() const { return true; } virtual void convertToPublic() { if(!sec) return; // extract the public key into DER format DSA *dsa_pkey = EVP_PKEY_get0_DSA(evp.pkey); int len = i2d_DSAPublicKey(dsa_pkey, NULL); SecureArray result(len); unsigned char *p = (unsigned char *)result.data(); i2d_DSAPublicKey(dsa_pkey, &p); p = (unsigned char *)result.data(); // put the DER public key back into openssl evp.reset(); DSA *dsa; #ifdef OSSL_097 dsa = d2i_DSAPublicKey(NULL, (const unsigned char **)&p, result.size()); #else dsa = d2i_DSAPublicKey(NULL, (unsigned char **)&p, result.size()); #endif evp.pkey = EVP_PKEY_new(); EVP_PKEY_assign_DSA(evp.pkey, dsa); sec = false; } virtual int bits() const { return EVP_PKEY_bits(evp.pkey); } virtual void startSign(SignatureAlgorithm, SignatureFormat format) { // openssl native format is DER, so transform otherwise if(format != DERSequence) transformsig = true; else transformsig = false; evp.startSign(EVP_sha1()); } virtual void startVerify(SignatureAlgorithm, SignatureFormat format) { // openssl native format is DER, so transform otherwise if(format != DERSequence) transformsig = true; else transformsig = false; evp.startVerify(EVP_sha1()); } virtual void update(const MemoryRegion &in) { evp.update(in); } virtual QByteArray endSign() { SecureArray out = evp.endSign(); if(transformsig) return dsasig_der_to_raw(out).toByteArray(); else return out.toByteArray(); } virtual bool endVerify(const QByteArray &sig) { SecureArray in; if(transformsig) in = dsasig_raw_to_der(sig); else in = sig; return evp.endVerify(in); } virtual void createPrivate(const DLGroup &domain, bool block) { evp.reset(); keymaker = new DSAKeyMaker(domain, !block ? this : 0); wasBlocking = block; if(block) { keymaker->run(); km_finished(); } else { connect(keymaker, SIGNAL(finished()), SLOT(km_finished())); keymaker->start(); } } virtual void createPrivate(const DLGroup &domain, const BigInteger &y, const BigInteger &x) { evp.reset(); DSA *dsa = DSA_new(); BIGNUM *bnp = bi2bn(domain.p()); BIGNUM *bnq = bi2bn(domain.q()); BIGNUM *bng = bi2bn(domain.g()); BIGNUM *bnpub_key = bi2bn(y); BIGNUM *bnpriv_key = bi2bn(x); if(!DSA_set0_pqg(dsa, bnp, bnq, bng) || !DSA_set0_key(dsa, bnpub_key, bnpriv_key)) { DSA_free(dsa); return; } evp.pkey = EVP_PKEY_new(); EVP_PKEY_assign_DSA(evp.pkey, dsa); sec = true; } virtual void createPublic(const DLGroup &domain, const BigInteger &y) { evp.reset(); DSA *dsa = DSA_new(); BIGNUM *bnp = bi2bn(domain.p()); BIGNUM *bnq = bi2bn(domain.q()); BIGNUM *bng = bi2bn(domain.g()); BIGNUM *bnpub_key = bi2bn(y); if(!DSA_set0_pqg(dsa, bnp, bnq, bng) || !DSA_set0_key(dsa, bnpub_key, NULL)) { DSA_free(dsa); return; } evp.pkey = EVP_PKEY_new(); EVP_PKEY_assign_DSA(evp.pkey, dsa); sec = false; } virtual DLGroup domain() const { DSA *dsa = EVP_PKEY_get0_DSA(evp.pkey); const BIGNUM *bnp, *bnq, *bng; DSA_get0_pqg(dsa, &bnp, &bnq, &bng); return DLGroup(bn2bi(bnp), bn2bi(bnq), bn2bi(bng)); } virtual BigInteger y() const { DSA *dsa = EVP_PKEY_get0_DSA(evp.pkey); const BIGNUM *bnpub_key; DSA_get0_key(dsa, &bnpub_key, NULL); return bn2bi(bnpub_key); } virtual BigInteger x() const { DSA *dsa = EVP_PKEY_get0_DSA(evp.pkey); const BIGNUM *bnpriv_key; DSA_get0_key(dsa, NULL, &bnpriv_key); return bn2bi(bnpriv_key); } private slots: void km_finished() { DSA *dsa = keymaker->takeResult(); if(wasBlocking) delete keymaker; else keymaker->deleteLater(); keymaker = 0; if(dsa) { evp.pkey = EVP_PKEY_new(); EVP_PKEY_assign_DSA(evp.pkey, dsa); sec = true; } if(!wasBlocking) emit finished(); } }; //---------------------------------------------------------------------------- // DHKey //---------------------------------------------------------------------------- class DHKeyMaker : public QThread { Q_OBJECT public: DLGroup domain; DH *result; DHKeyMaker(const DLGroup &_domain, QObject *parent = 0) : QThread(parent), domain(_domain), result(0) { } ~DHKeyMaker() { wait(); if(result) DH_free(result); } virtual void run() { DH *dh = DH_new(); BIGNUM *bnp = bi2bn(domain.p()); BIGNUM *bng = bi2bn(domain.g()); if(!DH_set0_pqg(dh, bnp, NULL, bng) || !DH_generate_key(dh)) { DH_free(dh); return; } result = dh; } DH *takeResult() { DH *dh = result; result = 0; return dh; } }; class DHKey : public DHContext { Q_OBJECT public: EVPKey evp; DHKeyMaker *keymaker; bool wasBlocking; bool sec; DHKey(Provider *p) : DHContext(p) { keymaker = 0; sec = false; } DHKey(const DHKey &from) : DHContext(from.provider()), evp(from.evp) { keymaker = 0; sec = from.sec; } ~DHKey() { delete keymaker; } virtual Provider::Context *clone() const { return new DHKey(*this); } virtual bool isNull() const { return (evp.pkey ? false: true); } virtual PKey::Type type() const { return PKey::DH; } virtual bool isPrivate() const { return sec; } virtual bool canExport() const { return true; } virtual void convertToPublic() { if(!sec) return; DH *orig = EVP_PKEY_get0_DH(evp.pkey); DH *dh = DH_new(); const BIGNUM *bnp, *bng, *bnpub_key; DH_get0_pqg(orig, &bnp, NULL, &bng); DH_get0_key(orig, &bnpub_key, NULL); DH_set0_key(dh, BN_dup(bnpub_key), NULL); DH_set0_pqg(dh, BN_dup(bnp), NULL, BN_dup(bng)); evp.reset(); evp.pkey = EVP_PKEY_new(); EVP_PKEY_assign_DH(evp.pkey, dh); sec = false; } virtual int bits() const { return EVP_PKEY_bits(evp.pkey); } virtual SymmetricKey deriveKey(const PKeyBase &theirs) { DH *dh = EVP_PKEY_get0_DH(evp.pkey); DH *them = EVP_PKEY_get0_DH(static_cast(&theirs)->evp.pkey); const BIGNUM *bnpub_key; DH_get0_key(them, &bnpub_key, NULL); SecureArray result(DH_size(dh)); int ret = DH_compute_key((unsigned char *)result.data(), bnpub_key, dh); if(ret <= 0) return SymmetricKey(); result.resize(ret); return SymmetricKey(result); } virtual void createPrivate(const DLGroup &domain, bool block) { evp.reset(); keymaker = new DHKeyMaker(domain, !block ? this : 0); wasBlocking = block; if(block) { keymaker->run(); km_finished(); } else { connect(keymaker, SIGNAL(finished()), SLOT(km_finished())); keymaker->start(); } } virtual void createPrivate(const DLGroup &domain, const BigInteger &y, const BigInteger &x) { evp.reset(); DH *dh = DH_new(); BIGNUM *bnp = bi2bn(domain.p()); BIGNUM *bng = bi2bn(domain.g()); BIGNUM *bnpub_key = bi2bn(y); BIGNUM *bnpriv_key = bi2bn(x); if(!DH_set0_key(dh, bnpub_key, bnpriv_key) || !DH_set0_pqg(dh, bnp, NULL, bng)) { DH_free(dh); return; } evp.pkey = EVP_PKEY_new(); EVP_PKEY_assign_DH(evp.pkey, dh); sec = true; } virtual void createPublic(const DLGroup &domain, const BigInteger &y) { evp.reset(); DH *dh = DH_new(); BIGNUM *bnp = bi2bn(domain.p()); BIGNUM *bng = bi2bn(domain.g()); BIGNUM *bnpub_key = bi2bn(y); if(!DH_set0_key(dh, bnpub_key, NULL) || !DH_set0_pqg(dh, bnp, NULL, bng)) { DH_free(dh); return; } evp.pkey = EVP_PKEY_new(); EVP_PKEY_assign_DH(evp.pkey, dh); sec = false; } virtual DLGroup domain() const { DH *dh = EVP_PKEY_get0_DH(evp.pkey); const BIGNUM *bnp, *bng; DH_get0_pqg(dh, &bnp, NULL, &bng); return DLGroup(bn2bi(bnp), bn2bi(bng)); } virtual BigInteger y() const { DH *dh = EVP_PKEY_get0_DH(evp.pkey); const BIGNUM *bnpub_key; DH_get0_key(dh, &bnpub_key, NULL); return bn2bi(bnpub_key); } virtual BigInteger x() const { DH *dh = EVP_PKEY_get0_DH(evp.pkey); const BIGNUM *bnpriv_key; DH_get0_key(dh, NULL, &bnpriv_key); return bn2bi(bnpriv_key); } private slots: void km_finished() { DH *dh = keymaker->takeResult(); if(wasBlocking) delete keymaker; else keymaker->deleteLater(); keymaker = 0; if(dh) { evp.pkey = EVP_PKEY_new(); EVP_PKEY_assign_DH(evp.pkey, dh); sec = true; } if(!wasBlocking) emit finished(); } }; //---------------------------------------------------------------------------- // QCA-based RSA_METHOD //---------------------------------------------------------------------------- // only supports EMSA3_Raw for now class QCA_RSA_METHOD { public: RSAPrivateKey key; QCA_RSA_METHOD(RSAPrivateKey _key, RSA *rsa) { key = _key; RSA_set_method(rsa, rsa_method()); #ifndef OSSL_110 rsa->flags |= RSA_FLAG_SIGN_VER; #endif RSA_set_app_data(rsa, this); BIGNUM *bnn = bi2bn(_key.n()); BIGNUM *bne = bi2bn(_key.e()); RSA_set0_key(rsa, bnn, bne, NULL); } RSA_METHOD *rsa_method() { static RSA_METHOD *ops = 0; if(!ops) { ops = RSA_meth_dup(RSA_get_default_method()); RSA_meth_set_priv_enc(ops, NULL); //pkcs11_rsa_encrypt RSA_meth_set_priv_dec(ops, rsa_priv_dec); //pkcs11_rsa_encrypt #ifdef OSSL_110 RSA_meth_set_sign(ops, NULL); #else RSA_meth_set_sign(ops, rsa_sign); #endif RSA_meth_set_verify(ops, NULL); //pkcs11_rsa_verify RSA_meth_set_finish(ops, rsa_finish); } return ops; } static int rsa_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { QCA::EncryptionAlgorithm algo; if (padding == RSA_PKCS1_PADDING) { algo = QCA::EME_PKCS1v15; } else if (padding == RSA_PKCS1_OAEP_PADDING) { algo = QCA::EME_PKCS1_OAEP; } else { RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT, RSA_R_UNKNOWN_PADDING_TYPE); return -1; } QCA_RSA_METHOD *self = (QCA_RSA_METHOD *)RSA_get_app_data(rsa); QCA::SecureArray input; input.resize(flen); memcpy(input.data(), from, input.size()); QCA::SecureArray output; if (self->key.decrypt(input, &output, algo)) { memcpy(to, output.data(), output.size()); return output.size(); } // XXX: An error should be set in this case too. return -1; } #ifndef OSSL_110 static int rsa_sign(int type, const unsigned char *m, unsigned int m_len, unsigned char *sigret, unsigned int *siglen, const RSA *rsa) { QCA_RSA_METHOD *self = (QCA_RSA_METHOD *)RSA_get_app_data(rsa); // TODO: this is disgusting unsigned char *p, *tmps = NULL; const unsigned char *s = NULL; int i,j; j = 0; if(type == NID_md5_sha1) { } else { // make X509 packet X509_SIG sig; ASN1_TYPE parameter; X509_ALGOR algor; ASN1_OCTET_STRING digest; int rsa_size = RSA_size(rsa); //int rsa_size = 128; //CK_ULONG sigsize = rsa_size; sig.algor= &algor; sig.algor->algorithm=OBJ_nid2obj(type); if (sig.algor->algorithm == NULL) { //RSAerr(RSA_F_RSA_SIGN,RSA_R_UNKNOWN_ALGORITHM_TYPE); return 0; } if (sig.algor->algorithm->length == 0) { //RSAerr(RSA_F_RSA_SIGN,RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD); return 0; } parameter.type=V_ASN1_NULL; parameter.value.ptr=NULL; sig.algor->parameter= ¶meter; sig.digest= &digest; sig.digest->data=(unsigned char *)m; /* TMP UGLY CAST */ sig.digest->length=m_len; i=i2d_X509_SIG(&sig,NULL); j=rsa_size; if (i > (j-RSA_PKCS1_PADDING_SIZE)) { //RSAerr(RSA_F_RSA_SIGN,RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY); return 0; } tmps=(unsigned char *)OPENSSL_malloc((unsigned int)j+1); if (tmps == NULL) { //RSAerr(RSA_F_RSA_SIGN,ERR_R_MALLOC_FAILURE); return 0; } p=tmps; i2d_X509_SIG(&sig,&p); s=tmps; m = s; m_len = i; } SecureArray input; input.resize(m_len); memcpy(input.data(), m, input.size()); SecureArray result = self->key.signMessage(input, EMSA3_Raw); if(tmps) { OPENSSL_cleanse(tmps,(unsigned int)j+1); OPENSSL_free(tmps); } // TODO: even though we return error here, PKCS7_sign will // not return error. what gives? if(result.isEmpty()) return 0; memcpy(sigret, result.data(), result.size()); *siglen = result.size(); return 1; } #endif static int rsa_finish(RSA *rsa) { QCA_RSA_METHOD *self = (QCA_RSA_METHOD *)RSA_get_app_data(rsa); delete self; return 1; } }; static RSA *createFromExisting(const RSAPrivateKey &key) { RSA *r = RSA_new(); new QCA_RSA_METHOD(key, r); // will delete itself on RSA_free return r; } //---------------------------------------------------------------------------- // MyPKeyContext //---------------------------------------------------------------------------- class MyPKeyContext : public PKeyContext { public: PKeyBase *k; MyPKeyContext(Provider *p) : PKeyContext(p) { k = 0; } ~MyPKeyContext() { delete k; } virtual Provider::Context *clone() const { MyPKeyContext *c = new MyPKeyContext(*this); c->k = (PKeyBase *)k->clone(); return c; } virtual QList supportedTypes() const { QList list; list += PKey::RSA; list += PKey::DSA; list += PKey::DH; return list; } virtual QList supportedIOTypes() const { QList list; list += PKey::RSA; list += PKey::DSA; return list; } virtual QList supportedPBEAlgorithms() const { QList list; list += PBES2_DES_SHA1; list += PBES2_TripleDES_SHA1; return list; } virtual PKeyBase *key() { return k; } virtual const PKeyBase *key() const { return k; } virtual void setKey(PKeyBase *key) { k = key; } virtual bool importKey(const PKeyBase *key) { Q_UNUSED(key); return false; } EVP_PKEY *get_pkey() const { PKey::Type t = k->type(); if(t == PKey::RSA) return static_cast(k)->evp.pkey; else if(t == PKey::DSA) return static_cast(k)->evp.pkey; else return static_cast(k)->evp.pkey; } PKeyBase *pkeyToBase(EVP_PKEY *pkey, bool sec) const { PKeyBase *nk = 0; int pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey)); if(pkey_type == EVP_PKEY_RSA) { RSAKey *c = new RSAKey(provider()); c->evp.pkey = pkey; c->sec = sec; nk = c; } else if(pkey_type == EVP_PKEY_DSA) { DSAKey *c = new DSAKey(provider()); c->evp.pkey = pkey; c->sec = sec; nk = c; } else if(pkey_type == EVP_PKEY_DH) { DHKey *c = new DHKey(provider()); c->evp.pkey = pkey; c->sec = sec; nk = c; } else { EVP_PKEY_free(pkey); } return nk; } virtual QByteArray publicToDER() const { EVP_PKEY *pkey = get_pkey(); int pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey)); // OpenSSL does not have DH import/export support if(pkey_type == EVP_PKEY_DH) return QByteArray(); BIO *bo = BIO_new(BIO_s_mem()); i2d_PUBKEY_bio(bo, pkey); QByteArray buf = bio2ba(bo); return buf; } virtual QString publicToPEM() const { EVP_PKEY *pkey = get_pkey(); int pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey)); // OpenSSL does not have DH import/export support if(pkey_type == EVP_PKEY_DH) return QString(); BIO *bo = BIO_new(BIO_s_mem()); PEM_write_bio_PUBKEY(bo, pkey); QByteArray buf = bio2ba(bo); return QString::fromLatin1(buf); } virtual ConvertResult publicFromDER(const QByteArray &in) { delete k; k = 0; BIO *bi = BIO_new(BIO_s_mem()); BIO_write(bi, in.data(), in.size()); EVP_PKEY *pkey = d2i_PUBKEY_bio(bi, NULL); BIO_free(bi); if(!pkey) return ErrorDecode; k = pkeyToBase(pkey, false); if(k) return ConvertGood; else return ErrorDecode; } virtual ConvertResult publicFromPEM(const QString &s) { delete k; k = 0; QByteArray in = s.toLatin1(); BIO *bi = BIO_new(BIO_s_mem()); BIO_write(bi, in.data(), in.size()); EVP_PKEY *pkey = PEM_read_bio_PUBKEY(bi, NULL, passphrase_cb, NULL); BIO_free(bi); if(!pkey) return ErrorDecode; k = pkeyToBase(pkey, false); if(k) return ConvertGood; else return ErrorDecode; } virtual SecureArray privateToDER(const SecureArray &passphrase, PBEAlgorithm pbe) const { //if(pbe == PBEDefault) // pbe = PBES2_TripleDES_SHA1; const EVP_CIPHER *cipher = 0; if(pbe == PBES2_TripleDES_SHA1) cipher = EVP_des_ede3_cbc(); else if(pbe == PBES2_DES_SHA1) cipher = EVP_des_cbc(); if(!cipher) return SecureArray(); EVP_PKEY *pkey = get_pkey(); int pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey)); // OpenSSL does not have DH import/export support if(pkey_type == EVP_PKEY_DH) return SecureArray(); BIO *bo = BIO_new(BIO_s_mem()); if(!passphrase.isEmpty()) i2d_PKCS8PrivateKey_bio(bo, pkey, cipher, NULL, 0, NULL, (void *)passphrase.data()); else i2d_PKCS8PrivateKey_bio(bo, pkey, NULL, NULL, 0, NULL, NULL); SecureArray buf = bio2buf(bo); return buf; } virtual QString privateToPEM(const SecureArray &passphrase, PBEAlgorithm pbe) const { //if(pbe == PBEDefault) // pbe = PBES2_TripleDES_SHA1; const EVP_CIPHER *cipher = 0; if(pbe == PBES2_TripleDES_SHA1) cipher = EVP_des_ede3_cbc(); else if(pbe == PBES2_DES_SHA1) cipher = EVP_des_cbc(); if(!cipher) return QString(); EVP_PKEY *pkey = get_pkey(); int pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey)); // OpenSSL does not have DH import/export support if(pkey_type == EVP_PKEY_DH) return QString(); BIO *bo = BIO_new(BIO_s_mem()); if(!passphrase.isEmpty()) PEM_write_bio_PKCS8PrivateKey(bo, pkey, cipher, NULL, 0, NULL, (void *)passphrase.data()); else PEM_write_bio_PKCS8PrivateKey(bo, pkey, NULL, NULL, 0, NULL, NULL); SecureArray buf = bio2buf(bo); return QString::fromLatin1(buf.toByteArray()); } virtual ConvertResult privateFromDER(const SecureArray &in, const SecureArray &passphrase) { delete k; k = 0; EVP_PKEY *pkey; if(!passphrase.isEmpty()) pkey = qca_d2i_PKCS8PrivateKey(in, NULL, NULL, (void *)passphrase.data()); else pkey = qca_d2i_PKCS8PrivateKey(in, NULL, passphrase_cb, NULL); if(!pkey) return ErrorDecode; k = pkeyToBase(pkey, true); if(k) return ConvertGood; else return ErrorDecode; } virtual ConvertResult privateFromPEM(const QString &s, const SecureArray &passphrase) { delete k; k = 0; QByteArray in = s.toLatin1(); BIO *bi = BIO_new(BIO_s_mem()); BIO_write(bi, in.data(), in.size()); EVP_PKEY *pkey; if(!passphrase.isEmpty()) pkey = PEM_read_bio_PrivateKey(bi, NULL, NULL, (void *)passphrase.data()); else pkey = PEM_read_bio_PrivateKey(bi, NULL, passphrase_cb, NULL); BIO_free(bi); if(!pkey) return ErrorDecode; k = pkeyToBase(pkey, true); if(k) return ConvertGood; else return ErrorDecode; } }; //---------------------------------------------------------------------------- // MyCertContext //---------------------------------------------------------------------------- class X509Item { public: X509 *cert; X509_REQ *req; X509_CRL *crl; enum Type { TypeCert, TypeReq, TypeCRL }; X509Item() { cert = 0; req = 0; crl = 0; } X509Item(const X509Item &from) { cert = 0; req = 0; crl = 0; *this = from; } ~X509Item() { reset(); } X509Item & operator=(const X509Item &from) { if(this != &from) { reset(); cert = from.cert; req = from.req; crl = from.crl; if(cert) X509_up_ref(cert); if(req) { #ifdef OSSL_110 // Not exposed, so copy req = X509_REQ_dup(req); #else CRYPTO_add(&req->references, 1, CRYPTO_LOCK_X509_REQ); #endif } if(crl) X509_CRL_up_ref(crl); } return *this; } void reset() { if(cert) { X509_free(cert); cert = 0; } if(req) { X509_REQ_free(req); req = 0; } if(crl) { X509_CRL_free(crl); crl = 0; } } bool isNull() const { return (!cert && !req && !crl); } QByteArray toDER() const { BIO *bo = BIO_new(BIO_s_mem()); if(cert) i2d_X509_bio(bo, cert); else if(req) i2d_X509_REQ_bio(bo, req); else if(crl) i2d_X509_CRL_bio(bo, crl); QByteArray buf = bio2ba(bo); return buf; } QString toPEM() const { BIO *bo = BIO_new(BIO_s_mem()); if(cert) PEM_write_bio_X509(bo, cert); else if(req) PEM_write_bio_X509_REQ(bo, req); else if(crl) PEM_write_bio_X509_CRL(bo, crl); QByteArray buf = bio2ba(bo); return QString::fromLatin1(buf); } ConvertResult fromDER(const QByteArray &in, Type t) { reset(); BIO *bi = BIO_new(BIO_s_mem()); BIO_write(bi, in.data(), in.size()); if(t == TypeCert) cert = d2i_X509_bio(bi, NULL); else if(t == TypeReq) req = d2i_X509_REQ_bio(bi, NULL); else if(t == TypeCRL) crl = d2i_X509_CRL_bio(bi, NULL); BIO_free(bi); if(isNull()) return ErrorDecode; return ConvertGood; } ConvertResult fromPEM(const QString &s, Type t) { reset(); QByteArray in = s.toLatin1(); BIO *bi = BIO_new(BIO_s_mem()); BIO_write(bi, in.data(), in.size()); if(t == TypeCert) cert = PEM_read_bio_X509(bi, NULL, passphrase_cb, NULL); else if(t == TypeReq) req = PEM_read_bio_X509_REQ(bi, NULL, passphrase_cb, NULL); else if(t == TypeCRL) crl = PEM_read_bio_X509_CRL(bi, NULL, passphrase_cb, NULL); BIO_free(bi); if(isNull()) return ErrorDecode; return ConvertGood; } }; // (taken from kdelibs) -- Justin // // This code is mostly taken from OpenSSL v0.9.5a // by Eric Young QDateTime ASN1_UTCTIME_QDateTime(const ASN1_UTCTIME *tm, int *isGmt) { QDateTime qdt; char *v; int gmt=0; int i; int y=0,M=0,d=0,h=0,m=0,s=0; QDate qdate; QTime qtime; i = tm->length; v = (char *)tm->data; if (i < 10) goto auq_err; if (v[i-1] == 'Z') gmt=1; for (i=0; i<10; i++) if ((v[i] > '9') || (v[i] < '0')) goto auq_err; y = (v[0]-'0')*10+(v[1]-'0'); if (y < 50) y+=100; M = (v[2]-'0')*10+(v[3]-'0'); if ((M > 12) || (M < 1)) goto auq_err; d = (v[4]-'0')*10+(v[5]-'0'); h = (v[6]-'0')*10+(v[7]-'0'); m = (v[8]-'0')*10+(v[9]-'0'); if ( (v[10] >= '0') && (v[10] <= '9') && (v[11] >= '0') && (v[11] <= '9')) s = (v[10]-'0')*10+(v[11]-'0'); // localize the date and display it. qdate.setDate(y+1900, M, d); qtime.setHMS(h,m,s); qdt.setDate(qdate); qdt.setTime(qtime); if (gmt) qdt.setTimeSpec(Qt::UTC); auq_err: if (isGmt) *isGmt = gmt; return qdt; } class MyCertContext; static bool sameChain(STACK_OF(X509) *ossl, const QList &qca); // TODO: support read/write of multiple info values with the same name class MyCertContext : public CertContext { public: X509Item item; CertContextProps _props; MyCertContext(Provider *p) : CertContext(p) { //printf("[%p] ** created\n", this); } MyCertContext(const MyCertContext &from) : CertContext(from), item(from.item), _props(from._props) { //printf("[%p] ** created as copy (from [%p])\n", this, &from); } ~MyCertContext() { //printf("[%p] ** deleted\n", this); } virtual Provider::Context *clone() const { return new MyCertContext(*this); } virtual QByteArray toDER() const { return item.toDER(); } virtual QString toPEM() const { return item.toPEM(); } virtual ConvertResult fromDER(const QByteArray &a) { _props = CertContextProps(); ConvertResult r = item.fromDER(a, X509Item::TypeCert); if(r == ConvertGood) make_props(); return r; } virtual ConvertResult fromPEM(const QString &s) { _props = CertContextProps(); ConvertResult r = item.fromPEM(s, X509Item::TypeCert); if(r == ConvertGood) make_props(); return r; } void fromX509(X509 *x) { X509_up_ref(x); item.cert = x; make_props(); } virtual bool createSelfSigned(const CertificateOptions &opts, const PKeyContext &priv) { _props = CertContextProps(); item.reset(); CertificateInfo info = opts.info(); // Note: removing default constraints, let the app choose these if it wants Constraints constraints = opts.constraints(); // constraints - logic from Botan /*Constraints constraints; if(opts.isCA()) { constraints += KeyCertificateSign; constraints += CRLSign; } else constraints = find_constraints(priv, opts.constraints());*/ EVP_PKEY *pk = static_cast(&priv)->get_pkey(); X509_EXTENSION *ex; const EVP_MD *md; if(priv.key()->type() == PKey::RSA) md = EVP_sha1(); else if(priv.key()->type() == PKey::DSA) md = EVP_sha1(); else return false; // create X509 *x = X509_new(); X509_set_version(x, 2); // serial BIGNUM *bn = bi2bn(opts.serialNumber()); BN_to_ASN1_INTEGER(bn, X509_get_serialNumber(x)); BN_free(bn); // validity period ASN1_TIME_set(X509_get_notBefore(x), opts.notValidBefore().toTime_t()); ASN1_TIME_set(X509_get_notAfter(x), opts.notValidAfter().toTime_t()); // public key X509_set_pubkey(x, pk); // subject X509_NAME *name = new_cert_name(info); X509_set_subject_name(x, name); // issuer == subject X509_set_issuer_name(x, name); // subject key id ex = new_subject_key_id(x); { X509_add_ext(x, ex, -1); X509_EXTENSION_free(ex); } // CA mode ex = new_basic_constraints(opts.isCA(), opts.pathLimit()); if(ex) { X509_add_ext(x, ex, -1); X509_EXTENSION_free(ex); } // subject alt name ex = new_cert_subject_alt_name(info); if(ex) { X509_add_ext(x, ex, -1); X509_EXTENSION_free(ex); } // key usage ex = new_cert_key_usage(constraints); if(ex) { X509_add_ext(x, ex, -1); X509_EXTENSION_free(ex); } // extended key usage ex = new_cert_ext_key_usage(constraints); if(ex) { X509_add_ext(x, ex, -1); X509_EXTENSION_free(ex); } // policies ex = new_cert_policies(opts.policies()); if(ex) { X509_add_ext(x, ex, -1); X509_EXTENSION_free(ex); } // finished X509_sign(x, pk, md); item.cert = x; make_props(); return true; } virtual const CertContextProps *props() const { //printf("[%p] grabbing props\n", this); return &_props; } virtual bool compare(const CertContext *other) const { const CertContextProps *a = &_props; const CertContextProps *b = other->props(); PublicKey akey, bkey; PKeyContext *ac = subjectPublicKey(); akey.change(ac); PKeyContext *bc = other->subjectPublicKey(); bkey.change(bc); // logic from Botan if(a->sig != b->sig || a->sigalgo != b->sigalgo || akey != bkey) return false; if(a->issuer != b->issuer || a->subject != b->subject) return false; if(a->serial != b->serial || a->version != b->version) return false; if(a->start != b->start || a->end != b->end) return false; return true; } // does a new virtual PKeyContext *subjectPublicKey() const { MyPKeyContext *kc = new MyPKeyContext(provider()); EVP_PKEY *pkey = X509_get_pubkey(item.cert); PKeyBase *kb = kc->pkeyToBase(pkey, false); kc->setKey(kb); return kc; } virtual bool isIssuerOf(const CertContext *other) const { // to check a single issuer, we make a list of 1 STACK_OF(X509) *untrusted_list = sk_X509_new_null(); const MyCertContext *our_cc = this; X509 *x = our_cc->item.cert; X509_up_ref(x); sk_X509_push(untrusted_list, x); const MyCertContext *other_cc = static_cast(other); X509 *ox = other_cc->item.cert; X509_STORE *store = X509_STORE_new(); X509_STORE_CTX *ctx = X509_STORE_CTX_new(); X509_STORE_CTX_init(ctx, store, ox, untrusted_list); // we don't care about the verify result here X509_verify_cert(ctx); // grab the chain, which may not be fully populated STACK_OF(X509) *chain = X509_STORE_CTX_get_chain(ctx); bool ok = false; // chain should be exactly 2 items QList expected; expected += other_cc; expected += our_cc; if(chain && sameChain(chain, expected)) ok = true; // cleanup X509_STORE_CTX_free(ctx); X509_STORE_free(store); sk_X509_pop_free(untrusted_list, X509_free); return ok; } // implemented later because it depends on MyCRLContext virtual Validity validate(const QList &trusted, const QList &untrusted, const QList &crls, UsageMode u, ValidateFlags vf) const; virtual Validity validate_chain(const QList &chain, const QList &trusted, const QList &crls, UsageMode u, ValidateFlags vf) const; void make_props() { X509 *x = item.cert; CertContextProps p; p.version = X509_get_version(x); ASN1_INTEGER *ai = X509_get_serialNumber(x); if(ai) { char *rep = i2s_ASN1_INTEGER(NULL, ai); QString str = rep; OPENSSL_free(rep); p.serial.fromString(str); } p.start = ASN1_UTCTIME_QDateTime(X509_get_notBefore(x), NULL); p.end = ASN1_UTCTIME_QDateTime(X509_get_notAfter(x), NULL); CertificateInfo subject, issuer; subject = get_cert_name(X509_get_subject_name(x)); issuer = get_cert_name(X509_get_issuer_name(x)); p.isSelfSigned = ( X509_V_OK == X509_check_issued( x, x ) ); p.isCA = false; p.pathLimit = 0; int pos = X509_get_ext_by_NID(x, NID_basic_constraints, -1); if(pos != -1) { X509_EXTENSION *ex = X509_get_ext(x, pos); if(ex) get_basic_constraints(ex, &p.isCA, &p.pathLimit); } pos = X509_get_ext_by_NID(x, NID_subject_alt_name, -1); if(pos != -1) { X509_EXTENSION *ex = X509_get_ext(x, pos); if(ex) subject.unite(get_cert_alt_name(ex)); } pos = X509_get_ext_by_NID(x, NID_issuer_alt_name, -1); if(pos != -1) { X509_EXTENSION *ex = X509_get_ext(x, pos); if(ex) issuer.unite(get_cert_alt_name(ex)); } pos = X509_get_ext_by_NID(x, NID_key_usage, -1); if(pos != -1) { X509_EXTENSION *ex = X509_get_ext(x, pos); if(ex) p.constraints = get_cert_key_usage(ex); } pos = X509_get_ext_by_NID(x, NID_ext_key_usage, -1); if(pos != -1) { X509_EXTENSION *ex = X509_get_ext(x, pos); if(ex) p.constraints += get_cert_ext_key_usage(ex); } pos = X509_get_ext_by_NID(x, NID_certificate_policies, -1); if(pos != -1) { X509_EXTENSION *ex = X509_get_ext(x, pos); if(ex) p.policies = get_cert_policies(ex); } #ifdef OSSL_110 const #endif ASN1_BIT_STRING *signature; X509_get0_signature(&signature, NULL, x); if(signature) { p.sig = QByteArray(signature->length, 0); for (int i=0; i< signature->length; i++) p.sig[i] = signature->data[i]; } switch( X509_get_signature_nid(x) ) { case NID_sha1WithRSAEncryption: p.sigalgo = QCA::EMSA3_SHA1; break; case NID_md5WithRSAEncryption: p.sigalgo = QCA::EMSA3_MD5; break; #ifdef HAVE_OPENSSL_MD2 case NID_md2WithRSAEncryption: p.sigalgo = QCA::EMSA3_MD2; break; #endif case NID_ripemd160WithRSA: p.sigalgo = QCA::EMSA3_RIPEMD160; break; case NID_dsaWithSHA1: p.sigalgo = QCA::EMSA1_SHA1; break; case NID_sha224WithRSAEncryption: p.sigalgo = QCA::EMSA3_SHA224; break; case NID_sha256WithRSAEncryption: p.sigalgo = QCA::EMSA3_SHA256; break; case NID_sha384WithRSAEncryption: p.sigalgo = QCA::EMSA3_SHA384; break; case NID_sha512WithRSAEncryption: p.sigalgo = QCA::EMSA3_SHA512; break; default: qDebug() << "Unknown signature value: " << X509_get_signature_nid(x); p.sigalgo = QCA::SignatureUnknown; } pos = X509_get_ext_by_NID(x, NID_subject_key_identifier, -1); if(pos != -1) { X509_EXTENSION *ex = X509_get_ext(x, pos); if(ex) p.subjectId += get_cert_subject_key_id(ex); } pos = X509_get_ext_by_NID(x, NID_authority_key_identifier, -1); if(pos != -1) { X509_EXTENSION *ex = X509_get_ext(x, pos); if(ex) p.issuerId += get_cert_issuer_key_id(ex); } // FIXME: super hack CertificateOptions opts; opts.setInfo(subject); p.subject = opts.infoOrdered(); opts.setInfo(issuer); p.issuer = opts.infoOrdered(); _props = p; //printf("[%p] made props: [%s]\n", this, _props.subject[CommonName].toLatin1().data()); } }; bool sameChain(STACK_OF(X509) *ossl, const QList &qca) { if(sk_X509_num(ossl) != qca.count()) return false; for(int n = 0; n < sk_X509_num(ossl); ++n) { X509 *a = sk_X509_value(ossl, n); X509 *b = qca[n]->item.cert; if(X509_cmp(a, b) != 0) return false; } return true; } //---------------------------------------------------------------------------- // MyCAContext //---------------------------------------------------------------------------- // Thanks to Pascal Patry class MyCAContext : public CAContext { public: X509Item caCert; MyPKeyContext *privateKey; MyCAContext(Provider *p) : CAContext(p) { privateKey = 0; } MyCAContext(const MyCAContext &from) : CAContext(from), caCert(from.caCert) { privateKey = static_cast(from.privateKey -> clone()); } ~MyCAContext() { delete privateKey; } virtual CertContext *certificate() const { MyCertContext *cert = new MyCertContext(provider()); cert->fromX509(caCert.cert); return cert; } virtual CertContext *createCertificate(const PKeyContext &pub, const CertificateOptions &opts) const { // TODO: implement Q_UNUSED(pub) Q_UNUSED(opts) return 0; } virtual CRLContext *createCRL(const QDateTime &nextUpdate) const { // TODO: implement Q_UNUSED(nextUpdate) return 0; } virtual void setup(const CertContext &cert, const PKeyContext &priv) { caCert = static_cast(cert).item; delete privateKey; privateKey = 0; privateKey = static_cast(priv.clone()); } virtual CertContext *signRequest(const CSRContext &req, const QDateTime ¬ValidAfter) const { MyCertContext *cert = 0; const EVP_MD *md = 0; X509 *x = 0; const CertContextProps &props = *req.props(); CertificateOptions subjectOpts; X509_NAME *subjectName = 0; X509_EXTENSION *ex = 0; if(privateKey -> key()->type() == PKey::RSA) md = EVP_sha1(); else if(privateKey -> key()->type() == PKey::DSA) md = EVP_sha1(); else return 0; cert = new MyCertContext(provider()); subjectOpts.setInfoOrdered(props.subject); subjectName = new_cert_name(subjectOpts.info()); // create x = X509_new(); X509_set_version(x, 2); // serial BIGNUM *bn = bi2bn(props.serial); BN_to_ASN1_INTEGER(bn, X509_get_serialNumber(x)); BN_free(bn); // validity period ASN1_TIME_set(X509_get_notBefore(x), QDateTime::currentDateTime().toUTC().toTime_t()); ASN1_TIME_set(X509_get_notAfter(x), notValidAfter.toTime_t()); X509_set_pubkey(x, static_cast(req.subjectPublicKey()) -> get_pkey()); X509_set_subject_name(x, subjectName); X509_set_issuer_name(x, X509_get_subject_name(caCert.cert)); // subject key id ex = new_subject_key_id(x); { X509_add_ext(x, ex, -1); X509_EXTENSION_free(ex); } // CA mode ex = new_basic_constraints(props.isCA, props.pathLimit); if(ex) { X509_add_ext(x, ex, -1); X509_EXTENSION_free(ex); } // subject alt name ex = new_cert_subject_alt_name(subjectOpts.info()); if(ex) { X509_add_ext(x, ex, -1); X509_EXTENSION_free(ex); } // key usage ex = new_cert_key_usage(props.constraints); if(ex) { X509_add_ext(x, ex, -1); X509_EXTENSION_free(ex); } // extended key usage ex = new_cert_ext_key_usage(props.constraints); if(ex) { X509_add_ext(x, ex, -1); X509_EXTENSION_free(ex); } // policies ex = new_cert_policies(props.policies); if(ex) { X509_add_ext(x, ex, -1); X509_EXTENSION_free(ex); } if(!X509_sign(x, privateKey->get_pkey(), md)) { X509_free(x); delete cert; return 0; } cert->fromX509(x); X509_free(x); return cert; } virtual CRLContext *updateCRL(const CRLContext &crl, const QList &entries, const QDateTime &nextUpdate) const { // TODO: implement Q_UNUSED(crl) Q_UNUSED(entries) Q_UNUSED(nextUpdate) return 0; } virtual Provider::Context *clone() const { return new MyCAContext(*this); } }; //---------------------------------------------------------------------------- // MyCSRContext //---------------------------------------------------------------------------- class MyCSRContext : public CSRContext { public: X509Item item; CertContextProps _props; MyCSRContext(Provider *p) : CSRContext(p) { } MyCSRContext(const MyCSRContext &from) : CSRContext(from), item(from.item), _props(from._props) { } virtual Provider::Context *clone() const { return new MyCSRContext(*this); } virtual QByteArray toDER() const { return item.toDER(); } virtual QString toPEM() const { return item.toPEM(); } virtual ConvertResult fromDER(const QByteArray &a) { _props = CertContextProps(); ConvertResult r = item.fromDER(a, X509Item::TypeReq); if(r == ConvertGood) make_props(); return r; } virtual ConvertResult fromPEM(const QString &s) { _props = CertContextProps(); ConvertResult r = item.fromPEM(s, X509Item::TypeReq); if(r == ConvertGood) make_props(); return r; } virtual bool canUseFormat(CertificateRequestFormat f) const { if(f == PKCS10) return true; return false; } virtual bool createRequest(const CertificateOptions &opts, const PKeyContext &priv) { _props = CertContextProps(); item.reset(); CertificateInfo info = opts.info(); // Note: removing default constraints, let the app choose these if it wants Constraints constraints = opts.constraints(); // constraints - logic from Botan /*Constraints constraints; if(opts.isCA()) { constraints += KeyCertificateSign; constraints += CRLSign; } else constraints = find_constraints(priv, opts.constraints());*/ EVP_PKEY *pk = static_cast(&priv)->get_pkey(); X509_EXTENSION *ex; const EVP_MD *md; if(priv.key()->type() == PKey::RSA) md = EVP_sha1(); else if(priv.key()->type() == PKey::DSA) md = EVP_sha1(); else return false; // create X509_REQ *x = X509_REQ_new(); // public key X509_REQ_set_pubkey(x, pk); // subject X509_NAME *name = new_cert_name(info); X509_REQ_set_subject_name(x, name); // challenge QByteArray cs = opts.challenge().toLatin1(); if(!cs.isEmpty()) X509_REQ_add1_attr_by_NID(x, NID_pkcs9_challengePassword, MBSTRING_UTF8, (const unsigned char *)cs.data(), -1); STACK_OF(X509_EXTENSION) *exts = sk_X509_EXTENSION_new_null(); // CA mode ex = new_basic_constraints(opts.isCA(), opts.pathLimit()); if(ex) sk_X509_EXTENSION_push(exts, ex); // subject alt name ex = new_cert_subject_alt_name(info); if(ex) sk_X509_EXTENSION_push(exts, ex); // key usage ex = new_cert_key_usage(constraints); if(ex) sk_X509_EXTENSION_push(exts, ex); // extended key usage ex = new_cert_ext_key_usage(constraints); if(ex) sk_X509_EXTENSION_push(exts, ex); // policies ex = new_cert_policies(opts.policies()); if(ex) sk_X509_EXTENSION_push(exts, ex); if(sk_X509_EXTENSION_num(exts) > 0) X509_REQ_add_extensions(x, exts); sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); // finished X509_REQ_sign(x, pk, md); item.req = x; make_props(); return true; } virtual const CertContextProps *props() const { return &_props; } virtual bool compare(const CSRContext *other) const { const CertContextProps *a = &_props; const CertContextProps *b = other->props(); PublicKey akey, bkey; PKeyContext *ac = subjectPublicKey(); akey.change(ac); PKeyContext *bc = other->subjectPublicKey(); bkey.change(bc); if(a->sig != b->sig || a->sigalgo != b->sigalgo || akey != bkey) return false; // TODO: Anything else we should compare? return true; } virtual PKeyContext *subjectPublicKey() const // does a new { MyPKeyContext *kc = new MyPKeyContext(provider()); EVP_PKEY *pkey = X509_REQ_get_pubkey(item.req); PKeyBase *kb = kc->pkeyToBase(pkey, false); kc->setKey(kb); return kc; } virtual QString toSPKAC() const { return QString(); } virtual ConvertResult fromSPKAC(const QString &s) { Q_UNUSED(s); return ErrorDecode; } void make_props() { X509_REQ *x = item.req; CertContextProps p; // TODO: QString challenge; p.format = PKCS10; CertificateInfo subject; subject = get_cert_name(X509_REQ_get_subject_name(x)); STACK_OF(X509_EXTENSION) *exts = X509_REQ_get_extensions(x); p.isCA = false; p.pathLimit = 0; int pos = X509v3_get_ext_by_NID(exts, NID_basic_constraints, -1); if(pos != -1) { X509_EXTENSION *ex = X509v3_get_ext(exts, pos); if(ex) get_basic_constraints(ex, &p.isCA, &p.pathLimit); } pos = X509v3_get_ext_by_NID(exts, NID_subject_alt_name, -1); if(pos != -1) { X509_EXTENSION *ex = X509v3_get_ext(exts, pos); if(ex) subject.unite(get_cert_alt_name(ex)); } pos = X509v3_get_ext_by_NID(exts, NID_key_usage, -1); if(pos != -1) { X509_EXTENSION *ex = X509v3_get_ext(exts, pos); if(ex) p.constraints = get_cert_key_usage(ex); } pos = X509v3_get_ext_by_NID(exts, NID_ext_key_usage, -1); if(pos != -1) { X509_EXTENSION *ex = X509v3_get_ext(exts, pos); if(ex) p.constraints += get_cert_ext_key_usage(ex); } pos = X509v3_get_ext_by_NID(exts, NID_certificate_policies, -1); if(pos != -1) { X509_EXTENSION *ex = X509v3_get_ext(exts, pos); if(ex) p.policies = get_cert_policies(ex); } sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); const ASN1_BIT_STRING *signature; X509_REQ_get0_signature(x, &signature, NULL); if(signature) { p.sig = QByteArray(signature->length, 0); for (int i=0; i< signature->length; i++) p.sig[i] = signature->data[i]; } switch( X509_REQ_get_signature_nid(x) ) { case NID_sha1WithRSAEncryption: p.sigalgo = QCA::EMSA3_SHA1; break; case NID_md5WithRSAEncryption: p.sigalgo = QCA::EMSA3_MD5; break; #ifdef HAVE_OPENSSL_MD2 case NID_md2WithRSAEncryption: p.sigalgo = QCA::EMSA3_MD2; break; #endif case NID_ripemd160WithRSA: p.sigalgo = QCA::EMSA3_RIPEMD160; break; case NID_dsaWithSHA1: p.sigalgo = QCA::EMSA1_SHA1; break; default: qDebug() << "Unknown signature value: " << X509_REQ_get_signature_nid(x); p.sigalgo = QCA::SignatureUnknown; } // FIXME: super hack CertificateOptions opts; opts.setInfo(subject); p.subject = opts.infoOrdered(); _props = p; } }; //---------------------------------------------------------------------------- // MyCRLContext //---------------------------------------------------------------------------- class MyCRLContext : public CRLContext { public: X509Item item; CRLContextProps _props; MyCRLContext(Provider *p) : CRLContext(p) { } MyCRLContext(const MyCRLContext &from) : CRLContext(from), item(from.item) { } virtual Provider::Context *clone() const { return new MyCRLContext(*this); } virtual QByteArray toDER() const { return item.toDER(); } virtual QString toPEM() const { return item.toPEM(); } virtual ConvertResult fromDER(const QByteArray &a) { _props = CRLContextProps(); ConvertResult r = item.fromDER(a, X509Item::TypeCRL); if(r == ConvertGood) make_props(); return r; } virtual ConvertResult fromPEM(const QString &s) { ConvertResult r = item.fromPEM(s, X509Item::TypeCRL); if(r == ConvertGood) make_props(); return r; } void fromX509(X509_CRL *x) { X509_CRL_up_ref(x); item.crl = x; make_props(); } virtual const CRLContextProps *props() const { return &_props; } virtual bool compare(const CRLContext *other) const { const CRLContextProps *a = &_props; const CRLContextProps *b = other->props(); if(a->issuer != b->issuer) return false; if(a->number != b->number) return false; if(a->thisUpdate != b->thisUpdate) return false; if(a->nextUpdate != b->nextUpdate) return false; if(a->revoked != b->revoked) return false; if(a->sig != b->sig) return false; if(a->sigalgo != b->sigalgo) return false; if(a->issuerId != b->issuerId) return false; return true; } void make_props() { X509_CRL *x = item.crl; CRLContextProps p; CertificateInfo issuer; issuer = get_cert_name(X509_CRL_get_issuer(x)); p.thisUpdate = ASN1_UTCTIME_QDateTime(X509_CRL_get0_lastUpdate(x), NULL); p.nextUpdate = ASN1_UTCTIME_QDateTime(X509_CRL_get0_nextUpdate(x), NULL); STACK_OF(X509_REVOKED)* revokeStack = X509_CRL_get_REVOKED(x); for (int i = 0; i < sk_X509_REVOKED_num(revokeStack); ++i) { X509_REVOKED *rev = sk_X509_REVOKED_value(revokeStack, i); BigInteger serial = bn2bi(ASN1_INTEGER_to_BN(X509_REVOKED_get0_serialNumber(rev), NULL)); QDateTime time = ASN1_UTCTIME_QDateTime( X509_REVOKED_get0_revocationDate(rev), NULL); QCA::CRLEntry::Reason reason = QCA::CRLEntry::Unspecified; int pos = X509_REVOKED_get_ext_by_NID(rev, NID_crl_reason, -1); if (pos != -1) { X509_EXTENSION *ex = X509_REVOKED_get_ext(rev, pos); if(ex) { int *result = (int*) X509V3_EXT_d2i(ex); switch (*result) { case 0: reason = QCA::CRLEntry::Unspecified; break; case 1: reason = QCA::CRLEntry::KeyCompromise; break; case 2: reason = QCA::CRLEntry::CACompromise; break; case 3: reason = QCA::CRLEntry::AffiliationChanged; break; case 4: reason = QCA::CRLEntry::Superseded; break; case 5: reason = QCA::CRLEntry::CessationOfOperation; break; case 6: reason = QCA::CRLEntry::CertificateHold; break; case 8: reason = QCA::CRLEntry::RemoveFromCRL; break; case 9: reason = QCA::CRLEntry::PrivilegeWithdrawn; break; case 10: reason = QCA::CRLEntry::AACompromise; break; default: reason = QCA::CRLEntry::Unspecified; break; } ASN1_INTEGER_free((ASN1_INTEGER*)result); } } CRLEntry thisEntry( serial, time, reason); p.revoked.append(thisEntry); } const ASN1_BIT_STRING *signature; X509_CRL_get0_signature(x, &signature, NULL); if(signature) { p.sig = QByteArray(signature->length, 0); for (int i=0; i< signature->length; i++) p.sig[i] = signature->data[i]; } switch( X509_CRL_get_signature_nid(x) ) { case NID_sha1WithRSAEncryption: p.sigalgo = QCA::EMSA3_SHA1; break; case NID_md5WithRSAEncryption: p.sigalgo = QCA::EMSA3_MD5; break; #ifdef HAVE_OPENSSL_MD2 case NID_md2WithRSAEncryption: p.sigalgo = QCA::EMSA3_MD2; break; #endif case NID_ripemd160WithRSA: p.sigalgo = QCA::EMSA3_RIPEMD160; break; case NID_dsaWithSHA1: p.sigalgo = QCA::EMSA1_SHA1; break; case NID_sha224WithRSAEncryption: p.sigalgo = QCA::EMSA3_SHA224; break; case NID_sha256WithRSAEncryption: p.sigalgo = QCA::EMSA3_SHA256; break; case NID_sha384WithRSAEncryption: p.sigalgo = QCA::EMSA3_SHA384; break; case NID_sha512WithRSAEncryption: p.sigalgo = QCA::EMSA3_SHA512; break; default: qWarning() << "Unknown signature value: " << X509_CRL_get_signature_nid(x); p.sigalgo = QCA::SignatureUnknown; } int pos = X509_CRL_get_ext_by_NID(x, NID_authority_key_identifier, -1); if(pos != -1) { X509_EXTENSION *ex = X509_CRL_get_ext(x, pos); if(ex) p.issuerId += get_cert_issuer_key_id(ex); } p.number = -1; pos = X509_CRL_get_ext_by_NID(x, NID_crl_number, -1); if(pos != -1) { X509_EXTENSION *ex = X509_CRL_get_ext(x, pos); if(ex) { int *result = (int*) X509V3_EXT_d2i(ex); p.number = (*result); ASN1_INTEGER_free((ASN1_INTEGER*)result); } } // FIXME: super hack CertificateOptions opts; opts.setInfo(issuer); p.issuer = opts.infoOrdered(); _props = p; } }; //---------------------------------------------------------------------------- // MyCertCollectionContext //---------------------------------------------------------------------------- class MyCertCollectionContext : public CertCollectionContext { Q_OBJECT public: MyCertCollectionContext(Provider *p) : CertCollectionContext(p) { } virtual Provider::Context *clone() const { return new MyCertCollectionContext(*this); } virtual QByteArray toPKCS7(const QList &certs, const QList &crls) const { // TODO: implement Q_UNUSED(certs); Q_UNUSED(crls); return QByteArray(); } virtual ConvertResult fromPKCS7(const QByteArray &a, QList *certs, QList *crls) const { BIO *bi = BIO_new(BIO_s_mem()); BIO_write(bi, a.data(), a.size()); PKCS7 *p7 = d2i_PKCS7_bio(bi, NULL); BIO_free(bi); if(!p7) return ErrorDecode; STACK_OF(X509) *xcerts = 0; STACK_OF(X509_CRL) *xcrls = 0; int i = OBJ_obj2nid(p7->type); if(i == NID_pkcs7_signed) { xcerts = p7->d.sign->cert; xcrls = p7->d.sign->crl; } else if(i == NID_pkcs7_signedAndEnveloped) { xcerts = p7->d.signed_and_enveloped->cert; xcrls = p7->d.signed_and_enveloped->crl; } QList _certs; QList _crls; if(xcerts) { for(int n = 0; n < sk_X509_num(xcerts); ++n) { MyCertContext *cc = new MyCertContext(provider()); cc->fromX509(sk_X509_value(xcerts, n)); _certs += cc; } } if(xcrls) { for(int n = 0; n < sk_X509_CRL_num(xcrls); ++n) { MyCRLContext *cc = new MyCRLContext(provider()); cc->fromX509(sk_X509_CRL_value(xcrls, n)); _crls += cc; } } PKCS7_free(p7); *certs = _certs; *crls = _crls; return ConvertGood; } }; static bool usage_check(const MyCertContext &cc, UsageMode u) { if (cc._props.constraints.isEmpty() ) { // then any usage is OK return true; } switch (u) { case UsageAny : return true; break; case UsageTLSServer : return cc._props.constraints.contains(ServerAuth); break; case UsageTLSClient : return cc._props.constraints.contains(ClientAuth); break; case UsageCodeSigning : return cc._props.constraints.contains(CodeSigning); break; case UsageEmailProtection : return cc._props.constraints.contains(EmailProtection); break; case UsageTimeStamping : return cc._props.constraints.contains(TimeStamping); break; case UsageCRLSigning : return cc._props.constraints.contains(CRLSign); break; default: return true; } } Validity MyCertContext::validate(const QList &trusted, const QList &untrusted, const QList &crls, UsageMode u, ValidateFlags vf) const { // TODO Q_UNUSED(vf); STACK_OF(X509) *trusted_list = sk_X509_new_null(); STACK_OF(X509) *untrusted_list = sk_X509_new_null(); QList crl_list; int n; for(n = 0; n < trusted.count(); ++n) { const MyCertContext *cc = static_cast(trusted[n]); X509 *x = cc->item.cert; X509_up_ref(x); sk_X509_push(trusted_list, x); } for(n = 0; n < untrusted.count(); ++n) { const MyCertContext *cc = static_cast(untrusted[n]); X509 *x = cc->item.cert; X509_up_ref(x); sk_X509_push(untrusted_list, x); } for(n = 0; n < crls.count(); ++n) { const MyCRLContext *cc = static_cast(crls[n]); X509_CRL *x = cc->item.crl; X509_CRL_up_ref(x); crl_list.append(x); } const MyCertContext *cc = this; X509 *x = cc->item.cert; // verification happens through a store "context" X509_STORE_CTX *ctx = X509_STORE_CTX_new(); // make a store of crls X509_STORE *store = X509_STORE_new(); for(int n = 0; n < crl_list.count(); ++n) X509_STORE_add_crl(store, crl_list[n]); // the first initialization handles untrusted certs, crls, and target cert X509_STORE_CTX_init(ctx, store, x, untrusted_list); // this initializes the trusted certs X509_STORE_CTX_trusted_stack(ctx, trusted_list); // verify! int ret = X509_verify_cert(ctx); int err = -1; if(!ret) err = X509_STORE_CTX_get_error(ctx); // cleanup X509_STORE_CTX_free(ctx); X509_STORE_free(store); sk_X509_pop_free(trusted_list, X509_free); sk_X509_pop_free(untrusted_list, X509_free); for(int n = 0; n < crl_list.count(); ++n) X509_CRL_free(crl_list[n]); if(!ret) return convert_verify_error(err); if(!usage_check(*cc, u)) return ErrorInvalidPurpose; return ValidityGood; } Validity MyCertContext::validate_chain(const QList &chain, const QList &trusted, const QList &crls, UsageMode u, ValidateFlags vf) const { // TODO Q_UNUSED(vf); STACK_OF(X509) *trusted_list = sk_X509_new_null(); STACK_OF(X509) *untrusted_list = sk_X509_new_null(); QList crl_list; int n; for(n = 0; n < trusted.count(); ++n) { const MyCertContext *cc = static_cast(trusted[n]); X509 *x = cc->item.cert; X509_up_ref(x); sk_X509_push(trusted_list, x); } for(n = 1; n < chain.count(); ++n) { const MyCertContext *cc = static_cast(chain[n]); X509 *x = cc->item.cert; X509_up_ref(x); sk_X509_push(untrusted_list, x); } for(n = 0; n < crls.count(); ++n) { const MyCRLContext *cc = static_cast(crls[n]); X509_CRL *x = cc->item.crl; X509_CRL_up_ref(x); crl_list.append(x); } const MyCertContext *cc = static_cast(chain[0]); X509 *x = cc->item.cert; // verification happens through a store "context" X509_STORE_CTX *ctx = X509_STORE_CTX_new(); // make a store of crls X509_STORE *store = X509_STORE_new(); for(int n = 0; n < crl_list.count(); ++n) X509_STORE_add_crl(store, crl_list[n]); // the first initialization handles untrusted certs, crls, and target cert X509_STORE_CTX_init(ctx, store, x, untrusted_list); // this initializes the trusted certs X509_STORE_CTX_trusted_stack(ctx, trusted_list); // verify! int ret = X509_verify_cert(ctx); int err = -1; if(!ret) err = X509_STORE_CTX_get_error(ctx); // grab the chain, which may not be fully populated STACK_OF(X509) *xchain = X509_STORE_CTX_get_chain(ctx); // make sure the chain is what we expect. the reason we need to do // this is because I don't think openssl cares about the order of // input. that is, if there's a chain A<-B<-C, and we input A as // the base cert, with B and C as the issuers, we will get a // successful validation regardless of whether the issuer list is // in the order B,C or C,B. we don't want an input chain of A,C,B // to be considered correct, so we must account for that here. QList expected; for(int n = 0; n < chain.count(); ++n) expected += static_cast(chain[n]); if(!xchain || !sameChain(xchain, expected)) err = ErrorValidityUnknown; // cleanup X509_STORE_CTX_free(ctx); X509_STORE_free(store); sk_X509_pop_free(trusted_list, X509_free); sk_X509_pop_free(untrusted_list, X509_free); for(int n = 0; n < crl_list.count(); ++n) X509_CRL_free(crl_list[n]); if(!ret) return convert_verify_error(err); if(!usage_check(*cc, u)) return ErrorInvalidPurpose; return ValidityGood; } class MyPKCS12Context : public PKCS12Context { public: MyPKCS12Context(Provider *p) : PKCS12Context(p) { } ~MyPKCS12Context() { } virtual Provider::Context *clone() const { return 0; } virtual QByteArray toPKCS12(const QString &name, const QList &chain, const PKeyContext &priv, const SecureArray &passphrase) const { if(chain.count() < 1) return QByteArray(); X509 *cert = static_cast(chain[0])->item.cert; STACK_OF(X509) *ca = sk_X509_new_null(); if(chain.count() > 1) { for(int n = 1; n < chain.count(); ++n) { X509 *x = static_cast(chain[n])->item.cert; X509_up_ref(x); sk_X509_push(ca, x); } } const MyPKeyContext &pk = static_cast(priv); PKCS12 *p12 = PKCS12_create((char *)passphrase.data(), (char *)name.toLatin1().data(), pk.get_pkey(), cert, ca, 0, 0, 0, 0, 0); sk_X509_pop_free(ca, X509_free); if(!p12) return QByteArray(); BIO *bo = BIO_new(BIO_s_mem()); i2d_PKCS12_bio(bo, p12); QByteArray out = bio2ba(bo); return out; } virtual ConvertResult fromPKCS12(const QByteArray &in, const SecureArray &passphrase, QString *name, QList *chain, PKeyContext **priv) const { BIO *bi = BIO_new(BIO_s_mem()); BIO_write(bi, in.data(), in.size()); PKCS12 *p12 = d2i_PKCS12_bio(bi, NULL); if(!p12) return ErrorDecode; EVP_PKEY *pkey; X509 *cert; STACK_OF(X509) *ca = NULL; if(!PKCS12_parse(p12, passphrase.data(), &pkey, &cert, &ca)) { PKCS12_free(p12); return ErrorDecode; } PKCS12_free(p12); // require private key if(!pkey) { if(cert) X509_free(cert); if(ca) sk_X509_pop_free(ca, X509_free); return ErrorDecode; } // TODO: require cert int aliasLength; char *aliasData = (char*)X509_alias_get0(cert, &aliasLength); *name = QString::fromLatin1(aliasData, aliasLength); MyPKeyContext *pk = new MyPKeyContext(provider()); PKeyBase *k = pk->pkeyToBase(pkey, true); // does an EVP_PKEY_free() pk->k = k; *priv = pk; QList certs; if(cert) { MyCertContext *cc = new MyCertContext(provider()); cc->fromX509(cert); certs.append(cc); X509_free(cert); } if(ca) { // TODO: reorder in chain-order? // TODO: throw out certs that don't fit the chain? for(int n = 0; n < sk_X509_num(ca); ++n) { MyCertContext *cc = new MyCertContext(provider()); cc->fromX509(sk_X509_value(ca, n)); certs.append(cc); } sk_X509_pop_free(ca, X509_free); } // reorder, throw out QCA::CertificateChain ch; for(int n = 0; n < certs.count(); ++n) { QCA::Certificate cert; cert.change(certs[n]); ch += cert; } certs.clear(); ch = ch.complete(QList()); for(int n = 0; n < ch.count(); ++n) { MyCertContext *cc = (MyCertContext *)ch[n].context(); certs += (new MyCertContext(*cc)); } ch.clear(); *chain = certs; return ConvertGood; } }; //========================================================== static QString cipherIDtoString( const TLS::Version &version, const unsigned long &cipherID) { if (TLS::TLS_v1 == version) { switch( cipherID & 0xFFFF ) { case 0x0000: // RFC 2246 A.5 return QString("TLS_NULL_WITH_NULL_NULL"); break; case 0x0001: // RFC 2246 A.5 return QString("TLS_RSA_WITH_NULL_MD5"); break; case 0x0002: // RFC 2246 A.5 return QString("TLS_RSA_WITH_NULL_SHA"); break; case 0x0003: // RFC 2246 A.5 return QString("TLS_RSA_EXPORT_WITH_RC4_40_MD5"); break; case 0x0004: // RFC 2246 A.5 return QString("TLS_RSA_WITH_RC4_128_MD5"); break; case 0x0005: // RFC 2246 A.5 return QString("TLS_RSA_WITH_RC4_128_SHA"); break; case 0x0006: // RFC 2246 A.5 return QString("TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5"); break; case 0x0007: // RFC 2246 A.5 return QString("TLS_RSA_WITH_IDEA_CBC_SHA"); break; case 0x0008: // RFC 2246 A.5 return QString("TLS_RSA_EXPORT_WITH_DES40_CBC_SHA"); break; case 0x0009: // RFC 2246 A.5 return QString("TLS_RSA_WITH_DES_CBC_SHA"); break; case 0x000A: // RFC 2246 A.5 return QString("TLS_RSA_WITH_3DES_EDE_CBC_SHA"); break; case 0x000B: // RFC 2246 A.5 return QString("TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA"); break; case 0x000C: // RFC 2246 A.5 return QString("TLS_DH_DSS_WITH_DES_CBC_SHA"); break; case 0x000D: // RFC 2246 A.5 return QString("TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA"); break; case 0x000E: // RFC 2246 A.5 return QString("TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"); break; case 0x000F: // RFC 2246 A.5 return QString("TLS_DH_RSA_WITH_DES_CBC_SHA"); break; case 0x0010: // RFC 2246 A.5 return QString("TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA"); break; case 0x0011: // RFC 2246 A.5 return QString("TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"); break; case 0x0012: // RFC 2246 A.5 return QString("TLS_DHE_DSS_WITH_DES_CBC_SHA"); break; case 0x0013: // RFC 2246 A.5 return QString("TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA"); break; case 0x0014: // RFC 2246 A.5 return QString("TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA"); break; case 0x0015: // RFC 2246 A.5 return QString("TLS_DHE_RSA_WITH_DES_CBC_SHA"); break; case 0x0016: // RFC 2246 A.5 return QString("TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA"); break; case 0x0017: // RFC 2246 A.5 return QString("TLS_DH_anon_EXPORT_WITH_RC4_40_MD5"); break; case 0x0018: // RFC 2246 A.5 return QString("TLS_DH_anon_WITH_RC4_128_MD5"); break; case 0x0019: // RFC 2246 A.5 return QString("TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA"); break; case 0x001A: // RFC 2246 A.5 return QString("TLS_DH_anon_WITH_DES_CBC_SHA"); break; case 0x001B: // RFC 2246 A.5 return QString("TLS_DH_anon_WITH_3DES_EDE_CBC_SHA"); break; // 0x001C and 0x001D are reserved to avoid collision with SSL3 Fortezza. case 0x001E: // RFC 2712 Section 3 return QString("TLS_KRB5_WITH_DES_CBC_SHA"); break; case 0x001F: // RFC 2712 Section 3 return QString("TLS_KRB5_WITH_3DES_EDE_CBC_SHA"); break; case 0x0020: // RFC 2712 Section 3 return QString("TLS_KRB5_WITH_RC4_128_SHA"); break; case 0x0021: // RFC 2712 Section 3 return QString("TLS_KRB5_WITH_IDEA_CBC_SHA"); break; case 0x0022: // RFC 2712 Section 3 return QString("TLS_KRB5_WITH_DES_CBC_MD5"); break; case 0x0023: // RFC 2712 Section 3 return QString("TLS_KRB5_WITH_3DES_EDE_CBC_MD5"); break; case 0x0024: // RFC 2712 Section 3 return QString("TLS_KRB5_WITH_RC4_128_MD5"); break; case 0x0025: // RFC 2712 Section 3 return QString("TLS_KRB5_WITH_IDEA_CBC_MD5"); break; case 0x0026: // RFC 2712 Section 3 return QString("TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA"); break; case 0x0027: // RFC 2712 Section 3 return QString("TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA"); break; case 0x0028: // RFC 2712 Section 3 return QString("TLS_KRB5_EXPORT_WITH_RC4_40_SHA"); break; case 0x0029: // RFC 2712 Section 3 return QString("TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5"); break; case 0x002A: // RFC 2712 Section 3 return QString("TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5"); break; case 0x002B: // RFC 2712 Section 3 return QString("TLS_KRB5_EXPORT_WITH_RC4_40_MD5"); break; case 0x002F: // RFC 3268 return QString("TLS_RSA_WITH_AES_128_CBC_SHA"); break; case 0x0030: // RFC 3268 return QString("TLS_DH_DSS_WITH_AES_128_CBC_SHA"); break; case 0x0031: // RFC 3268 return QString("TLS_DH_RSA_WITH_AES_128_CBC_SHA"); break; case 0x0032: // RFC 3268 return QString("TLS_DHE_DSS_WITH_AES_128_CBC_SHA"); break; case 0x0033: // RFC 3268 return QString("TLS_DHE_RSA_WITH_AES_128_CBC_SHA"); break; case 0x0034: // RFC 3268 return QString("TLS_DH_anon_WITH_AES_128_CBC_SHA"); break; case 0x0035: // RFC 3268 return QString("TLS_RSA_WITH_AES_256_CBC_SHA"); break; case 0x0036: // RFC 3268 return QString("TLS_DH_DSS_WITH_AES_256_CBC_SHA"); break; case 0x0037: // RFC 3268 return QString("TLS_DH_RSA_WITH_AES_256_CBC_SHA"); break; case 0x0038: // RFC 3268 return QString("TLS_DHE_DSS_WITH_AES_256_CBC_SHA"); break; case 0x0039: // RFC 3268 return QString("TLS_DHE_RSA_WITH_AES_256_CBC_SHA"); break; case 0x003A: // RFC 3268 return QString("TLS_DH_anon_WITH_AES_256_CBC_SHA"); break; // TODO: 0x0041 -> 0x0046 are from RFC4132 (Camellia) case 0x0060: // Was meant to be from draft-ietf-tls-56-bit-ciphersuites-01.txt, but isn't return QString("TLS_CK_RSA_EXPORT1024_WITH_RC4_56_MD5"); break; case 0x0061: // Was meant to be from draft-ietf-tls-56-bit-ciphersuites-01.txt, but isn't return QString("TLS_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5"); break; case 0x0062: // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt return QString("TLS_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA"); break; case 0x0063: // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt return QString("TLS_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA"); break; case 0x0064: // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt return QString("TLS_CK_RSA_EXPORT1024_WITH_RC4_56_SHA"); break; case 0x0065: // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt return QString("TLS_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA"); break; case 0x0066: // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt return QString("TLS_CK_DHE_DSS_WITH_RC4_128_SHA"); break; // TODO: 0x0084 -> 0x0089 are from RFC4132 (Camellia) // TODO: 0x008A -> 0x0095 are from RFC4279 (PSK) // TODO: 0xC000 -> 0xC019 are from the ECC draft default: return QString("TLS algo to be added: %1").arg(cipherID & 0xffff, 0, 16); break; } } else if (TLS::SSL_v3 == version) { switch( cipherID & 0xFFFF ) { case 0x0000: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_NULL_WITH_NULL_NULL"); break; case 0x0001: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_RSA_WITH_NULL_MD5"); break; case 0x0002: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_RSA_WITH_NULL_SHA"); break; case 0x0003: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_RSA_EXPORT_WITH_RC4_40_MD5"); break; case 0x0004: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_RSA_WITH_RC4_128_MD5"); break; case 0x0005: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_RSA_WITH_RC4_128_SHA"); break; case 0x0006: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5"); break; case 0x0007: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_RSA_WITH_IDEA_CBC_SHA"); break; case 0x0008: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA"); break; case 0x0009: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_RSA_WITH_DES_CBC_SHA"); break; case 0x000A: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_RSA_WITH_3DES_EDE_CBC_SHA"); break; case 0x000B: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA"); break; case 0x000C: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_DH_DSS_WITH_DES_CBC_SHA"); break; case 0x000D: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA"); break; case 0x000E: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_DH_RSA_WITH_DES_CBC_SHA"); break; case 0x000F: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_DH_RSA_WITH_DES_CBC_SHA"); break; case 0x0010: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA"); break; case 0x0011: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"); break; case 0x0012: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_DHE_DSS_WITH_DES_CBC_SHA"); break; case 0x0013: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA"); break; case 0x0014: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA"); break; case 0x0015: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_DHE_RSA_WITH_DES_CBC_SHA"); break; case 0x0016: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA"); break; case 0x0017: // From the Netscape SSL3 Draft (nov 1996) return QString("SL_DH_anon_EXPORT_WITH_RC4_40_MD5"); break; case 0x0018: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_DH_anon_WITH_RC4_128_MD5"); break; case 0x0019: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA"); break; case 0x001A: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_DH_anon_WITH_DES_CBC_SHA"); break; case 0x001B: // From the Netscape SSL3 Draft (nov 1996) return QString("SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"); break; // TODO: Sort out the Fortezza mess... // These aren't in the Netscape SSL3 draft, but openssl does // allow you to use them with SSL3. case 0x001E: return QString("SSL_KRB5_WITH_DES_CBC_SHA"); break; case 0x001F: return QString("SSL_KRB5_WITH_3DES_EDE_CBC_SHA"); break; case 0x0020: return QString("SSL_KRB5_WITH_RC4_128_SHA"); break; case 0x0021: return QString("SSL_KRB5_WITH_IDEA_CBC_SHA"); break; case 0x0022: return QString("SSL_KRB5_WITH_DES_CBC_MD5"); break; case 0x0023: return QString("SSL_KRB5_WITH_3DES_EDE_CBC_MD5"); break; case 0x0024: return QString("SSL_KRB5_WITH_RC4_128_MD5"); break; case 0x0025: return QString("SSL_KRB5_WITH_IDEA_CBC_MD5"); break; case 0x0026: return QString("SSL_KRB5_EXPORT_WITH_DES_CBC_40_SHA"); break; case 0x0027: return QString("SSL_KRB5_EXPORT_WITH_RC2_CBC_40_SHA"); break; case 0x0028: return QString("SSL_KRB5_EXPORT_WITH_RC4_40_SHA"); break; case 0x0029: return QString("SSL_KRB5_EXPORT_WITH_DES_CBC_40_MD5"); break; case 0x002A: return QString("SSL_KRB5_EXPORT_WITH_RC2_CBC_40_MD5"); break; case 0x002B: return QString("SSL_KRB5_EXPORT_WITH_RC4_40_MD5"); break; case 0x002F: return QString("SSL_RSA_WITH_AES_128_CBC_SHA"); break; case 0x0030: return QString("SSL_DH_DSS_WITH_AES_128_CBC_SHA"); break; case 0x0031: return QString("SSL_DH_RSA_WITH_AES_128_CBC_SHA"); break; case 0x0032: return QString("SSL_DHE_DSS_WITH_AES_128_CBC_SHA"); break; case 0x0033: return QString("SSL_DHE_RSA_WITH_AES_128_CBC_SHA"); break; case 0x0034: return QString("SSL_DH_anon_WITH_AES_128_CBC_SHA"); break; case 0x0035: return QString("SSL_RSA_WITH_AES_256_CBC_SHA"); break; case 0x0036: return QString("SSL_DH_DSS_WITH_AES_256_CBC_SHA"); break; case 0x0037: return QString("SSL_DH_RSA_WITH_AES_256_CBC_SHA"); break; case 0x0038: return QString("SSL_DHE_DSS_WITH_AES_256_CBC_SHA"); break; case 0x0039: return QString("SSL_DHE_RSA_WITH_AES_256_CBC_SHA"); break; case 0x003A: return QString("SSL_DH_anon_WITH_AES_256_CBC_SHA"); break; case 0x0060: // Was meant to be from draft-ietf-tls-56-bit-ciphersuites-01.txt, but isn't return QString("SSL_CK_RSA_EXPORT1024_WITH_RC4_56_MD5"); break; case 0x0061: // Was meant to be from draft-ietf-tls-56-bit-ciphersuites-01.txt, but isn't return QString("SSL_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5"); break; case 0x0062: // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt return QString("SSL_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA"); break; case 0x0063: // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt return QString("SSL_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA"); break; case 0x0064: // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt return QString("SSL_CK_RSA_EXPORT1024_WITH_RC4_56_SHA"); break; case 0x0065: // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt return QString("SSL_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA"); break; case 0x0066: // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt return QString("SSL_CK_DHE_DSS_WITH_RC4_128_SHA"); break; default: return QString("SSL3 to be added: %1").arg(cipherID & 0xffff, 0, 16); break; } } else if (TLS::SSL_v2 == version) { switch( cipherID & 0xffffff) { case 0x010080: // From the Netscape SSL2 Draft Section C.4 (nov 1994) return QString("SSL_CK_RC4_128_WITH_MD5"); break; case 0x020080: // From the Netscape SSL2 Draft Section C.4 (nov 1994) return QString("SSL_CK_RC4_128_EXPORT40_WITH_MD5"); break; case 0x030080: // From the Netscape SSL2 Draft Section C.4 (nov 1994) return QString("SSL_CK_RC2_128_CBC_WITH_MD5"); break; case 0x040080: // From the Netscape SSL2 Draft Section C.4 (nov 1994) return QString("SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5"); break; case 0x050080: // From the Netscape SSL2 Draft Section C.4 (nov 1994) return QString("SSL_CK_RC4_128_EXPORT40_WITH_MD5"); break; case 0x060040: // From the Netscape SSL2 Draft Section C.4 (nov 1994) return QString("SSL_CK_DES_64_CBC_WITH_MD5"); break; case 0x0700C0: // From the Netscape SSL2 Draft Section C.4 (nov 1994) return QString("SSL_CK_DES_192_EDE3_CBC_WITH_MD5"); break; case 0x080080: // From the openssl source, which says "MS hack" return QString("SSL_CK_RC4_64_WITH_MD5"); break; default: return QString("SSL2 to be added: %1").arg(cipherID & 0xffffff, 0, 16); break; } } else { return QString("Unknown version!"); } } // TODO: test to ensure there is no cert-test lag static bool ssl_init = false; class MyTLSContext : public TLSContext { public: enum { Good, TryAgain, Bad }; enum { Idle, Connect, Accept, Handshake, Active, Closing }; bool serv; // true if we are acting as a server int mode; QByteArray sendQueue; QByteArray recvQueue; CertificateCollection trusted; Certificate cert, peercert; // TODO: support cert chains PrivateKey key; QString targetHostName; Result result_result; QByteArray result_to_net; int result_encoded; QByteArray result_plain; SSL *ssl; #if OPENSSL_VERSION_NUMBER >= 0x00909000L const SSL_METHOD *method; #else SSL_METHOD *method; #endif SSL_CTX *context; BIO *rbio, *wbio; Validity vr; bool v_eof; MyTLSContext(Provider *p) : TLSContext(p, "tls") { if(!ssl_init) { SSL_library_init(); SSL_load_error_strings(); ssl_init = true; } ssl = 0; context = 0; reset(); } ~MyTLSContext() { reset(); } virtual Provider::Context *clone() const { return 0; } virtual void reset() { if(ssl) { SSL_free(ssl); ssl = 0; } if(context) { SSL_CTX_free(context); context = 0; } cert = Certificate(); key = PrivateKey(); sendQueue.resize(0); recvQueue.resize(0); mode = Idle; peercert = Certificate(); vr = ErrorValidityUnknown; v_eof = false; } // dummy verification function for SSL_set_verify() static int ssl_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) { Q_UNUSED(preverify_ok); Q_UNUSED(x509_ctx); // don't terminate handshake in case of verification failure return 1; } virtual QStringList supportedCipherSuites(const TLS::Version &version) const { OpenSSL_add_ssl_algorithms(); SSL_CTX *ctx = 0; switch (version) { #if !defined(OPENSSL_NO_SSL2) && !defined(OSSL_110) case TLS::SSL_v2: ctx = SSL_CTX_new(SSLv2_client_method()); break; #endif #ifndef OPENSSL_NO_SSL3_METHOD case TLS::SSL_v3: ctx = SSL_CTX_new(SSLv3_client_method()); break; #endif case TLS::TLS_v1: ctx = SSL_CTX_new(TLSv1_client_method()); break; case TLS::DTLS_v1: default: /* should not happen - should be in a "dtls" provider*/ qWarning("Unexpected enum in cipherSuites"); ctx = 0; } if (NULL == ctx) return QStringList(); SSL *ssl = SSL_new(ctx); if (NULL == ssl) { SSL_CTX_free(ctx); return QStringList(); } STACK_OF(SSL_CIPHER) *sk = SSL_get_ciphers(ssl); QStringList cipherList; for(int i = 0; i < sk_SSL_CIPHER_num(sk); ++i) { const SSL_CIPHER *thisCipher = sk_SSL_CIPHER_value(sk, i); cipherList += cipherIDtoString(version, SSL_CIPHER_get_id(thisCipher)); } SSL_free(ssl); SSL_CTX_free(ctx); return cipherList; } virtual bool canCompress() const { // TODO return false; } virtual bool canSetHostName() const { // TODO return false; } virtual int maxSSF() const { // TODO return 256; } virtual void setConstraints(int minSSF, int maxSSF) { // TODO Q_UNUSED(minSSF); Q_UNUSED(maxSSF); } virtual void setConstraints(const QStringList &cipherSuiteList) { // TODO Q_UNUSED(cipherSuiteList); } virtual void setup(bool serverMode, const QString &hostName, bool compress) { serv = serverMode; if ( false == serverMode ) { // client targetHostName = hostName; } Q_UNUSED(compress); // TODO } virtual void setTrustedCertificates(const CertificateCollection &_trusted) { trusted = _trusted; } virtual void setIssuerList(const QList &issuerList) { Q_UNUSED(issuerList); // TODO } virtual void setCertificate(const CertificateChain &_cert, const PrivateKey &_key) { if(!_cert.isEmpty()) cert = _cert.primary(); // TODO: take the whole chain key = _key; } virtual void setSessionId(const TLSSessionContext &id) { // TODO Q_UNUSED(id); } virtual void shutdown() { mode = Closing; } virtual void start() { bool ok; if(serv) ok = priv_startServer(); else ok = priv_startClient(); result_result = ok ? Success : Error; doResultsReady(); } virtual void update(const QByteArray &from_net, const QByteArray &from_app) { if(mode == Active) { bool ok = true; if(!from_app.isEmpty()) ok = priv_encode(from_app, &result_to_net, &result_encoded); if(ok) ok = priv_decode(from_net, &result_plain, &result_to_net); result_result = ok ? Success : Error; } else if(mode == Closing) result_result = priv_shutdown(from_net, &result_to_net); else result_result = priv_handshake(from_net, &result_to_net); //printf("update (from_net=%d, to_net=%d, from_app=%d, to_app=%d)\n", from_net.size(), result_to_net.size(), from_app.size(), result_plain.size()); doResultsReady(); } bool priv_startClient() { //serv = false; method = SSLv23_client_method(); if(!init()) return false; mode = Connect; return true; } bool priv_startServer() { //serv = true; method = SSLv23_server_method(); if(!init()) return false; mode = Accept; return true; } Result priv_handshake(const QByteArray &from_net, QByteArray *to_net) { if(!from_net.isEmpty()) BIO_write(rbio, from_net.data(), from_net.size()); if(mode == Connect) { int ret = doConnect(); if(ret == Good) { mode = Handshake; } else if(ret == Bad) { reset(); return Error; } } if(mode == Accept) { int ret = doAccept(); if(ret == Good) { getCert(); mode = Active; } else if(ret == Bad) { reset(); return Error; } } if(mode == Handshake) { int ret = doHandshake(); if(ret == Good) { getCert(); mode = Active; } else if(ret == Bad) { reset(); return Error; } } // process outgoing *to_net = readOutgoing(); if(mode == Active) return Success; else return Continue; } Result priv_shutdown(const QByteArray &from_net, QByteArray *to_net) { if(!from_net.isEmpty()) BIO_write(rbio, from_net.data(), from_net.size()); int ret = doShutdown(); if(ret == Bad) { reset(); return Error; } *to_net = readOutgoing(); if(ret == Good) { mode = Idle; return Success; } else { //mode = Closing; return Continue; } } bool priv_encode(const QByteArray &plain, QByteArray *to_net, int *enc) { if(mode != Active) return false; sendQueue.append(plain); int encoded = 0; if(sendQueue.size() > 0) { int ret = SSL_write(ssl, sendQueue.data(), sendQueue.size()); enum { Good, Continue, Done, Error }; int m; if(ret <= 0) { int x = SSL_get_error(ssl, ret); if(x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE) m = Continue; else if(x == SSL_ERROR_ZERO_RETURN) m = Done; else m = Error; } else { m = Good; encoded = ret; int newsize = sendQueue.size() - encoded; char *r = sendQueue.data(); memmove(r, r + encoded, newsize); sendQueue.resize(newsize); } if(m == Done) { sendQueue.resize(0); v_eof = true; return false; } if(m == Error) { sendQueue.resize(0); return false; } } *to_net += readOutgoing(); *enc = encoded; return true; } bool priv_decode(const QByteArray &from_net, QByteArray *plain, QByteArray *to_net) { if(mode != Active) return false; if(!from_net.isEmpty()) BIO_write(rbio, from_net.data(), from_net.size()); QByteArray a; while(!v_eof) { a.resize(8192); int ret = SSL_read(ssl, a.data(), a.size()); //printf("SSL_read = %d\n", ret); if(ret > 0) { if(ret != (int)a.size()) a.resize(ret); //printf("SSL_read chunk: [%s]\n", qPrintable(arrayToHex(a))); recvQueue.append(a); } else if(ret <= 0) { ERR_print_errors_fp(stdout); int x = SSL_get_error(ssl, ret); //printf("SSL_read error = %d\n", x); if(x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE) break; else if(x == SSL_ERROR_ZERO_RETURN) v_eof = true; else return false; } } *plain = recvQueue; recvQueue.resize(0); // could be outgoing data also *to_net += readOutgoing(); return true; } virtual bool waitForResultsReady(int msecs) { // TODO: for now, all operations block anyway Q_UNUSED(msecs); return true; } virtual Result result() const { return result_result; } virtual QByteArray to_net() { QByteArray a = result_to_net; result_to_net.clear(); return a; } virtual int encoded() const { return result_encoded; } virtual QByteArray to_app() { QByteArray a = result_plain; result_plain.clear(); return a; } virtual bool eof() const { return v_eof; } virtual bool clientHelloReceived() const { // TODO return false; } virtual bool serverHelloReceived() const { // TODO return false; } virtual QString hostName() const { // TODO return QString(); } virtual bool certificateRequested() const { // TODO return false; } virtual QList issuerList() const { // TODO return QList(); } virtual SessionInfo sessionInfo() const { SessionInfo sessInfo; SSL_SESSION *session = SSL_get0_session(ssl); sessInfo.isCompressed = (0 != SSL_SESSION_get_compress_id(session)); int ssl_version = SSL_version(ssl); if (ssl_version == TLS1_VERSION) sessInfo.version = TLS::TLS_v1; else if (ssl_version == SSL3_VERSION) sessInfo.version = TLS::SSL_v3; else if (ssl_version == SSL2_VERSION) sessInfo.version = TLS::SSL_v2; else { qDebug("unexpected version response"); sessInfo.version = TLS::TLS_v1; } sessInfo.cipherSuite = cipherIDtoString( sessInfo.version, SSL_CIPHER_get_id(SSL_get_current_cipher(ssl))); sessInfo.cipherMaxBits = SSL_get_cipher_bits(ssl, &(sessInfo.cipherBits)); sessInfo.id = 0; // TODO: session resuming return sessInfo; } virtual QByteArray unprocessed() { QByteArray a; int size = BIO_pending(rbio); if(size <= 0) return a; a.resize(size); int r = BIO_read(rbio, a.data(), size); if(r <= 0) { a.resize(0); return a; } if(r != size) a.resize(r); return a; } virtual Validity peerCertificateValidity() const { return vr; } virtual CertificateChain peerCertificateChain() const { // TODO: support whole chain CertificateChain chain; chain.append(peercert); return chain; } void doResultsReady() { QMetaObject::invokeMethod(this, "resultsReady", Qt::QueuedConnection); } bool init() { context = SSL_CTX_new(method); if(!context) return false; // setup the cert store { X509_STORE *store = SSL_CTX_get_cert_store(context); QList cert_list = trusted.certificates(); QList crl_list = trusted.crls(); int n; for(n = 0; n < cert_list.count(); ++n) { const MyCertContext *cc = static_cast(cert_list[n].context()); X509 *x = cc->item.cert; //CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509); X509_STORE_add_cert(store, x); } for(n = 0; n < crl_list.count(); ++n) { const MyCRLContext *cc = static_cast(crl_list[n].context()); X509_CRL *x = cc->item.crl; //CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509_CRL); X509_STORE_add_crl(store, x); } } ssl = SSL_new(context); if(!ssl) { SSL_CTX_free(context); context = 0; return false; } SSL_set_ssl_method(ssl, method); // can this return error? #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME if ( targetHostName.isEmpty() == false ) { // we have a target // this might fail, but we ignore that for now char *hostname = targetHostName.toLatin1().data(); SSL_set_tlsext_host_name( ssl, hostname ); } #endif // setup the memory bio rbio = BIO_new(BIO_s_mem()); wbio = BIO_new(BIO_s_mem()); // this passes control of the bios to ssl. we don't need to free them. SSL_set_bio(ssl, rbio, wbio); // FIXME: move this to after server hello // setup the cert to send if(!cert.isNull() && !key.isNull()) { PrivateKey nkey = key; const PKeyContext *tmp_kc = static_cast(nkey.context()); if(!tmp_kc->sameProvider(this)) { //fprintf(stderr, "experimental: private key supplied by a different provider\n"); // make a pkey pointing to the existing private key EVP_PKEY *pkey; pkey = EVP_PKEY_new(); EVP_PKEY_assign_RSA(pkey, createFromExisting(nkey.toRSA())); // make a new private key object to hold it MyPKeyContext *pk = new MyPKeyContext(provider()); PKeyBase *k = pk->pkeyToBase(pkey, true); // does an EVP_PKEY_free() pk->k = k; nkey.change(pk); } const MyCertContext *cc = static_cast(cert.context()); const MyPKeyContext *kc = static_cast(nkey.context()); if(SSL_use_certificate(ssl, cc->item.cert) != 1) { SSL_free(ssl); SSL_CTX_free(context); return false; } if(SSL_use_PrivateKey(ssl, kc->get_pkey()) != 1) { SSL_free(ssl); SSL_CTX_free(context); return false; } } // request a certificate from the client, if in server mode if(serv) { SSL_set_verify(ssl, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE, ssl_verify_callback); } return true; } void getCert() { // verify the certificate Validity code = ErrorValidityUnknown; STACK_OF(X509) *x_chain = SSL_get_peer_cert_chain(ssl); //X509 *x = SSL_get_peer_certificate(ssl); if(x_chain) { CertificateChain chain; if(serv) { X509 *x = SSL_get_peer_certificate(ssl); MyCertContext *cc = new MyCertContext(provider()); cc->fromX509(x); Certificate cert; cert.change(cc); chain += cert; } for(int n = 0; n < sk_X509_num(x_chain); ++n) { X509 *x = sk_X509_value(x_chain, n); MyCertContext *cc = new MyCertContext(provider()); cc->fromX509(x); Certificate cert; cert.change(cc); chain += cert; } peercert = chain.primary(); #ifdef Q_OS_MAC code = chain.validate(trusted); #else int ret = SSL_get_verify_result(ssl); if(ret == X509_V_OK) code = ValidityGood; else code = convert_verify_error(ret); #endif } else { peercert = Certificate(); } vr = code; } int doConnect() { int ret = SSL_connect(ssl); if(ret < 0) { int x = SSL_get_error(ssl, ret); if(x == SSL_ERROR_WANT_CONNECT || x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE) return TryAgain; else return Bad; } else if(ret == 0) return Bad; return Good; } int doAccept() { int ret = SSL_accept(ssl); if(ret < 0) { int x = SSL_get_error(ssl, ret); if(x == SSL_ERROR_WANT_CONNECT || x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE) return TryAgain; else return Bad; } else if(ret == 0) return Bad; return Good; } int doHandshake() { int ret = SSL_do_handshake(ssl); if(ret < 0) { int x = SSL_get_error(ssl, ret); if(x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE) return TryAgain; else return Bad; } else if(ret == 0) return Bad; return Good; } int doShutdown() { int ret = SSL_shutdown(ssl); if(ret >= 1) return Good; else { if(ret == 0) return TryAgain; int x = SSL_get_error(ssl, ret); if(x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE) return TryAgain; return Bad; } } QByteArray readOutgoing() { QByteArray a; int size = BIO_pending(wbio); if(size <= 0) return a; a.resize(size); int r = BIO_read(wbio, a.data(), size); if(r <= 0) { a.resize(0); return a; } if(r != size) a.resize(r); return a; } }; class CMSContext : public SMSContext { public: CertificateCollection trustedCerts; CertificateCollection untrustedCerts; QList privateKeys; CMSContext(Provider *p) : SMSContext(p, "cms") { } ~CMSContext() { } virtual Provider::Context *clone() const { return 0; } virtual void setTrustedCertificates(const CertificateCollection &trusted) { trustedCerts = trusted; } virtual void setUntrustedCertificates(const CertificateCollection &untrusted) { untrustedCerts = untrusted; } virtual void setPrivateKeys(const QList &keys) { privateKeys = keys; } virtual MessageContext *createMessage(); }; STACK_OF(X509) *get_pk7_certs(PKCS7 *p7) { int i = OBJ_obj2nid(p7->type); if(i == NID_pkcs7_signed) return p7->d.sign->cert; else if(i == NID_pkcs7_signedAndEnveloped) return p7->d.signed_and_enveloped->cert; else return 0; } class MyMessageContextThread : public QThread { Q_OBJECT public: SecureMessage::Format format; SecureMessage::SignMode signMode; Certificate cert; PrivateKey key; STACK_OF(X509) *other_certs; BIO *bi; int flags; PKCS7 *p7; bool ok; QByteArray out, sig; MyMessageContextThread(QObject *parent = 0) : QThread(parent), ok(false) { } protected: virtual void run() { MyCertContext *cc = static_cast(cert.context()); MyPKeyContext *kc = static_cast(key.context()); X509 *cx = cc->item.cert; EVP_PKEY *kx = kc->get_pkey(); p7 = PKCS7_sign(cx, kx, other_certs, bi, flags); BIO_free(bi); sk_X509_pop_free(other_certs, X509_free); if(p7) { //printf("good\n"); BIO *bo; //BIO *bo = BIO_new(BIO_s_mem()); //i2d_PKCS7_bio(bo, p7); //PEM_write_bio_PKCS7(bo, p7); //SecureArray buf = bio2buf(bo); //printf("[%s]\n", buf.data()); bo = BIO_new(BIO_s_mem()); if(format == SecureMessage::Binary) i2d_PKCS7_bio(bo, p7); else // Ascii PEM_write_bio_PKCS7(bo, p7); if (SecureMessage::Detached == signMode) sig = bio2ba(bo); else out = bio2ba(bo); ok = true; } else { printf("bad here\n"); ERR_print_errors_fp(stdout); } } }; class MyMessageContext : public MessageContext { Q_OBJECT public: CMSContext *cms; SecureMessageKey signer; SecureMessageKeyList to; SecureMessage::SignMode signMode; bool bundleSigner; bool smime; SecureMessage::Format format; Operation op; bool _finished; QByteArray in, out; QByteArray sig; int total; CertificateChain signerChain; int ver_ret; MyMessageContextThread *thread; MyMessageContext(CMSContext *_cms, Provider *p) : MessageContext(p, "cmsmsg") { cms = _cms; total = 0; ver_ret = 0; thread = 0; } ~MyMessageContext() { } virtual Provider::Context *clone() const { return 0; } virtual bool canSignMultiple() const { return false; } virtual SecureMessage::Type type() const { return SecureMessage::CMS; } virtual void reset() { } virtual void setupEncrypt(const SecureMessageKeyList &keys) { to = keys; } virtual void setupSign(const SecureMessageKeyList &keys, SecureMessage::SignMode m, bool bundleSigner, bool smime) { signer = keys.first(); signMode = m; this->bundleSigner = bundleSigner; this->smime = smime; } virtual void setupVerify(const QByteArray &detachedSig) { // TODO sig = detachedSig; } virtual void start(SecureMessage::Format f, Operation op) { format = f; _finished = false; // TODO: other operations //if(op == Sign) //{ this->op = op; //} //else if(op == Encrypt) //{ // this->op = op; //} } virtual void update(const QByteArray &in) { this->in.append(in); total += in.size(); QMetaObject::invokeMethod(this, "updated", Qt::QueuedConnection); } virtual QByteArray read() { return out; } virtual int written() { int x = total; total = 0; return x; } virtual void end() { _finished = true; // sign if(op == Sign) { CertificateChain chain = signer.x509CertificateChain(); Certificate cert = chain.primary(); QList nonroots; if(chain.count() > 1) { for(int n = 1; n < chain.count(); ++n) nonroots.append(chain[n]); } PrivateKey key = signer.x509PrivateKey(); const PKeyContext *tmp_kc = static_cast(key.context()); if(!tmp_kc->sameProvider(this)) { //fprintf(stderr, "experimental: private key supplied by a different provider\n"); // make a pkey pointing to the existing private key EVP_PKEY *pkey; pkey = EVP_PKEY_new(); EVP_PKEY_assign_RSA(pkey, createFromExisting(key.toRSA())); // make a new private key object to hold it MyPKeyContext *pk = new MyPKeyContext(provider()); PKeyBase *k = pk->pkeyToBase(pkey, true); // does an EVP_PKEY_free() pk->k = k; key.change(pk); } // allow different cert provider. this is just a // quick hack, enough to please qca-test if(!cert.context()->sameProvider(this)) { //fprintf(stderr, "experimental: cert supplied by a different provider\n"); cert = Certificate::fromDER(cert.toDER()); if(cert.isNull() || !cert.context()->sameProvider(this)) { //fprintf(stderr, "error converting cert\n"); } } //MyCertContext *cc = static_cast(cert.context()); //MyPKeyContext *kc = static_cast(key.context()); //X509 *cx = cc->item.cert; //EVP_PKEY *kx = kc->get_pkey(); STACK_OF(X509) *other_certs; BIO *bi; int flags; //PKCS7 *p7; // nonroots other_certs = sk_X509_new_null(); for(int n = 0; n < nonroots.count(); ++n) { X509 *x = static_cast(nonroots[n].context())->item.cert; X509_up_ref(x); sk_X509_push(other_certs, x); } //printf("bundling %d other_certs\n", sk_X509_num(other_certs)); bi = BIO_new(BIO_s_mem()); BIO_write(bi, in.data(), in.size()); flags = 0; flags |= PKCS7_BINARY; if (SecureMessage::Detached == signMode) { flags |= PKCS7_DETACHED; } if (false == bundleSigner) flags |= PKCS7_NOCERTS; if(thread) delete thread; thread = new MyMessageContextThread(this); thread->format = format; thread->signMode = signMode; thread->cert = cert; thread->key = key; thread->other_certs = other_certs; thread->bi = bi; thread->flags = flags; connect(thread, SIGNAL(finished()), SLOT(thread_finished())); thread->start(); } else if(op == Encrypt) { // TODO: support multiple recipients Certificate target = to.first().x509CertificateChain().primary(); STACK_OF(X509) *other_certs; BIO *bi; int flags; PKCS7 *p7; other_certs = sk_X509_new_null(); X509 *x = static_cast(target.context())->item.cert; X509_up_ref(x); sk_X509_push(other_certs, x); bi = BIO_new(BIO_s_mem()); BIO_write(bi, in.data(), in.size()); flags = 0; flags |= PKCS7_BINARY; p7 = PKCS7_encrypt(other_certs, bi, EVP_des_ede3_cbc(), flags); // TODO: cipher? BIO_free(bi); sk_X509_pop_free(other_certs, X509_free); QString env; if(p7) { // FIXME: format BIO *bo = BIO_new(BIO_s_mem()); i2d_PKCS7_bio(bo, p7); //PEM_write_bio_PKCS7(bo, p7); out = bio2ba(bo); PKCS7_free(p7); } else { printf("bad\n"); return; } } else if(op == Verify) { // TODO: support non-detached sigs BIO *out = BIO_new(BIO_s_mem()); BIO *bi = BIO_new(BIO_s_mem()); if (false == sig.isEmpty()) { // We have detached signature BIO_write(bi, sig.data(), sig.size()); } else { BIO_write(bi, in.data(), in.size()); } PKCS7 *p7; if(format == SecureMessage::Binary) p7 = d2i_PKCS7_bio(bi, NULL); else // Ascii p7 = PEM_read_bio_PKCS7(bi, NULL, passphrase_cb, NULL); BIO_free(bi); if(!p7) { // TODO printf("bad1\n"); QMetaObject::invokeMethod(this, "updated", Qt::QueuedConnection); return; } // intermediates/signers that may not be in the blob STACK_OF(X509) *other_certs = sk_X509_new_null(); QList untrusted_list = cms->untrustedCerts.certificates(); QList untrusted_crls = cms->untrustedCerts.crls(); // we'll use the crls later for(int n = 0; n < untrusted_list.count(); ++n) { X509 *x = static_cast(untrusted_list[n].context())->item.cert; X509_up_ref(x); sk_X509_push(other_certs, x); } // get the possible message signers QList signers; STACK_OF(X509) *xs = PKCS7_get0_signers(p7, other_certs, 0); if(xs) { for(int n = 0; n < sk_X509_num(xs); ++n) { MyCertContext *cc = new MyCertContext(provider()); cc->fromX509(sk_X509_value(xs, n)); Certificate cert; cert.change(cc); //printf("signer: [%s]\n", qPrintable(cert.commonName())); signers.append(cert); } sk_X509_free(xs); } // get the rest of the certificates lying around QList others; xs = get_pk7_certs(p7); // don't free if(xs) { for(int n = 0; n < sk_X509_num(xs); ++n) { MyCertContext *cc = new MyCertContext(provider()); cc->fromX509(sk_X509_value(xs, n)); Certificate cert; cert.change(cc); others.append(cert); //printf("other: [%s]\n", qPrintable(cert.commonName())); } } // signer needs to be supplied in the message itself // or via cms->untrustedCerts if(signers.isEmpty()) { QMetaObject::invokeMethod(this, "updated", Qt::QueuedConnection); return; } // FIXME: handle more than one signer CertificateChain chain; chain += signers[0]; // build chain chain = chain.complete(others); signerChain = chain; X509_STORE *store = X509_STORE_new(); QList cert_list = cms->trustedCerts.certificates(); QList crl_list = cms->trustedCerts.crls(); for(int n = 0; n < cert_list.count(); ++n) { //printf("trusted: [%s]\n", qPrintable(cert_list[n].commonName())); const MyCertContext *cc = static_cast(cert_list[n].context()); X509 *x = cc->item.cert; //CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509); X509_STORE_add_cert(store, x); } for(int n = 0; n < crl_list.count(); ++n) { const MyCRLContext *cc = static_cast(crl_list[n].context()); X509_CRL *x = cc->item.crl; //CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509_CRL); X509_STORE_add_crl(store, x); } // add these crls also crl_list = untrusted_crls; for(int n = 0; n < crl_list.count(); ++n) { const MyCRLContext *cc = static_cast(crl_list[n].context()); X509_CRL *x = cc->item.crl; //CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509_CRL); X509_STORE_add_crl(store, x); } int ret; if(!sig.isEmpty()) { // Detached signMode bi = BIO_new(BIO_s_mem()); BIO_write(bi, in.data(), in.size()); ret = PKCS7_verify(p7, other_certs, store, bi, NULL, 0); BIO_free(bi); } else { ret = PKCS7_verify(p7, other_certs, store, NULL, out, 0); // qDebug() << "Verify: " << ret; } //if(!ret) // ERR_print_errors_fp(stdout); sk_X509_pop_free(other_certs, X509_free); X509_STORE_free(store); PKCS7_free(p7); ver_ret = ret; // TODO QMetaObject::invokeMethod(this, "updated", Qt::QueuedConnection); } else if(op == Decrypt) { bool ok = false; for(int n = 0; n < cms->privateKeys.count(); ++n) { CertificateChain chain = cms->privateKeys[n].x509CertificateChain(); Certificate cert = chain.primary(); PrivateKey key = cms->privateKeys[n].x509PrivateKey(); MyCertContext *cc = static_cast(cert.context()); MyPKeyContext *kc = static_cast(key.context()); X509 *cx = cc->item.cert; EVP_PKEY *kx = kc->get_pkey(); BIO *bi = BIO_new(BIO_s_mem()); BIO_write(bi, in.data(), in.size()); PKCS7 *p7 = d2i_PKCS7_bio(bi, NULL); BIO_free(bi); if(!p7) { // TODO printf("bad1\n"); return; } BIO *bo = BIO_new(BIO_s_mem()); int ret = PKCS7_decrypt(p7, kx, cx, bo, 0); PKCS7_free(p7); if(!ret) continue; ok = true; out = bio2ba(bo); break; } if(!ok) { // TODO printf("bad2\n"); return; } } } virtual bool finished() const { return _finished; } virtual bool waitForFinished(int msecs) { // TODO Q_UNUSED(msecs); if(thread) { thread->wait(); getresults(); } return true; } virtual bool success() const { // TODO return true; } virtual SecureMessage::Error errorCode() const { // TODO return SecureMessage::ErrorUnknown; } virtual QByteArray signature() const { return sig; } virtual QString hashName() const { // TODO return "sha1"; } virtual SecureMessageSignatureList signers() const { // only report signers for verify if(op != Verify) return SecureMessageSignatureList(); SecureMessageKey key; if(!signerChain.isEmpty()) key.setX509CertificateChain(signerChain); // TODO/FIXME !!! InvalidSignature might be used here even // if the signature is just fine, and the key is invalid // (we need to use InvalidKey instead). Validity vr = ErrorValidityUnknown; if(!signerChain.isEmpty()) vr = signerChain.validate(cms->trustedCerts, cms->untrustedCerts.crls()); SecureMessageSignature::IdentityResult ir; if(vr == ValidityGood) ir = SecureMessageSignature::Valid; else ir = SecureMessageSignature::InvalidKey; if(!ver_ret) ir = SecureMessageSignature::InvalidSignature; SecureMessageSignature s(ir, vr, key, QDateTime::currentDateTime()); // TODO return SecureMessageSignatureList() << s; } void getresults() { sig = thread->sig; out = thread->out; } private slots: void thread_finished() { getresults(); emit updated(); } }; MessageContext *CMSContext::createMessage() { return new MyMessageContext(this, provider()); } class opensslCipherContext : public CipherContext { public: opensslCipherContext(const EVP_CIPHER *algorithm, const int pad, Provider *p, const QString &type) : CipherContext(p, type) { m_cryptoAlgorithm = algorithm; m_context = EVP_CIPHER_CTX_new(); EVP_CIPHER_CTX_init(m_context); m_pad = pad; m_type = type; } opensslCipherContext(const opensslCipherContext &other) : CipherContext(other) { m_cryptoAlgorithm = other.m_cryptoAlgorithm; m_context = EVP_CIPHER_CTX_new(); EVP_CIPHER_CTX_copy(m_context, other.m_context); m_direction = other.m_direction; m_pad = other.m_pad; m_type = other.m_type; m_tag = other.m_tag; } ~opensslCipherContext() { EVP_CIPHER_CTX_cleanup(m_context); EVP_CIPHER_CTX_free(m_context); } void setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv, const AuthTag &tag) { m_tag = tag; m_direction = dir; if ( ( m_cryptoAlgorithm == EVP_des_ede3() ) && (key.size() == 16) ) { // this is really a two key version of triple DES. m_cryptoAlgorithm = EVP_des_ede(); } if (Encode == m_direction) { EVP_EncryptInit_ex(m_context, m_cryptoAlgorithm, 0, 0, 0); EVP_CIPHER_CTX_set_key_length(m_context, key.size()); if (m_type.endsWith("gcm") || m_type.endsWith("ccm")) { int parameter = m_type.endsWith("gcm") ? EVP_CTRL_GCM_SET_IVLEN : EVP_CTRL_CCM_SET_IVLEN; EVP_CIPHER_CTX_ctrl(m_context, parameter, iv.size(), NULL); } EVP_EncryptInit_ex(m_context, 0, 0, (const unsigned char*)(key.data()), (const unsigned char*)(iv.data())); } else { EVP_DecryptInit_ex(m_context, m_cryptoAlgorithm, 0, 0, 0); EVP_CIPHER_CTX_set_key_length(m_context, key.size()); if (m_type.endsWith("gcm") || m_type.endsWith("ccm")) { int parameter = m_type.endsWith("gcm") ? EVP_CTRL_GCM_SET_IVLEN : EVP_CTRL_CCM_SET_IVLEN; EVP_CIPHER_CTX_ctrl(m_context, parameter, iv.size(), NULL); } EVP_DecryptInit_ex(m_context, 0, 0, (const unsigned char*)(key.data()), (const unsigned char*)(iv.data())); } EVP_CIPHER_CTX_set_padding(m_context, m_pad); } Provider::Context *clone() const { return new opensslCipherContext( *this ); } int blockSize() const { return EVP_CIPHER_CTX_block_size(m_context); } AuthTag tag() const { return m_tag; } bool update(const SecureArray &in, SecureArray *out) { // This works around a problem in OpenSSL, where it asserts if // there is nothing to encrypt. if ( 0 == in.size() ) return true; out->resize(in.size()+blockSize()); int resultLength; if (Encode == m_direction) { if (0 == EVP_EncryptUpdate(m_context, (unsigned char*)out->data(), &resultLength, (unsigned char*)in.data(), in.size())) { return false; } } else { if (0 == EVP_DecryptUpdate(m_context, (unsigned char*)out->data(), &resultLength, (unsigned char*)in.data(), in.size())) { return false; } } out->resize(resultLength); return true; } bool final(SecureArray *out) { out->resize(blockSize()); int resultLength; if (Encode == m_direction) { if (0 == EVP_EncryptFinal_ex(m_context, (unsigned char*)out->data(), &resultLength)) { return false; } if (m_tag.size() && (m_type.endsWith("gcm") || m_type.endsWith("ccm"))) { int parameter = m_type.endsWith("gcm") ? EVP_CTRL_GCM_GET_TAG : EVP_CTRL_CCM_GET_TAG; if (0 == EVP_CIPHER_CTX_ctrl(m_context, parameter, m_tag.size(), (unsigned char*)m_tag.data())) { return false; } } } else { if (m_tag.size() && (m_type.endsWith("gcm") || m_type.endsWith("ccm"))) { int parameter = m_type.endsWith("gcm") ? EVP_CTRL_GCM_SET_TAG : EVP_CTRL_CCM_SET_TAG; if (0 == EVP_CIPHER_CTX_ctrl(m_context, parameter, m_tag.size(), m_tag.data())) { return false; } } if (0 == EVP_DecryptFinal_ex(m_context, (unsigned char*)out->data(), &resultLength)) { return false; } } out->resize(resultLength); return true; } // Change cipher names KeyLength keyLength() const { if (m_type.left(4) == "des-") { return KeyLength( 8, 8, 1); } else if (m_type.left(6) == "aes128") { return KeyLength( 16, 16, 1); } else if (m_type.left(6) == "aes192") { return KeyLength( 24, 24, 1); } else if (m_type.left(6) == "aes256") { return KeyLength( 32, 32, 1); } else if (m_type.left(5) == "cast5") { return KeyLength( 5, 16, 1); } else if (m_type.left(8) == "blowfish") { // Don't know - TODO return KeyLength( 1, 32, 1); } else if (m_type.left(9) == "tripledes") { return KeyLength( 16, 24, 1); } else { return KeyLength( 0, 1, 1); } } protected: EVP_CIPHER_CTX *m_context; const EVP_CIPHER *m_cryptoAlgorithm; Direction m_direction; int m_pad; QString m_type; AuthTag m_tag; }; static QStringList all_hash_types() { QStringList list; list += "sha1"; #ifdef HAVE_OPENSSL_SHA0 list += "sha0"; #endif list += "ripemd160"; #ifdef HAVE_OPENSSL_MD2 list += "md2"; #endif list += "md4"; list += "md5"; #ifdef SHA224_DIGEST_LENGTH list += "sha224"; #endif #ifdef SHA256_DIGEST_LENGTH list += "sha256"; #endif #ifdef SHA384_DIGEST_LENGTH list += "sha384"; #endif #ifdef SHA512_DIGEST_LENGTH list += "sha512"; #endif /* #ifdef OBJ_whirlpool list += "whirlpool"; #endif */ return list; } static QStringList all_cipher_types() { QStringList list; list += "aes128-ecb"; list += "aes128-cfb"; list += "aes128-cbc"; list += "aes128-cbc-pkcs7"; list += "aes128-ofb"; #ifdef HAVE_OPENSSL_AES_CTR list += "aes128-ctr"; #endif #ifdef HAVE_OPENSSL_AES_GCM list += "aes128-gcm"; #endif #ifdef HAVE_OPENSSL_AES_CCM list += "aes128-ccm"; #endif list += "aes192-ecb"; list += "aes192-cfb"; list += "aes192-cbc"; list += "aes192-cbc-pkcs7"; list += "aes192-ofb"; #ifdef HAVE_OPENSSL_AES_CTR list += "aes192-ctr"; #endif #ifdef HAVE_OPENSSL_AES_GCM list += "aes192-gcm"; #endif #ifdef HAVE_OPENSSL_AES_CCM list += "aes192-ccm"; #endif list += "aes256-ecb"; list += "aes256-cbc"; list += "aes256-cbc-pkcs7"; list += "aes256-cfb"; list += "aes256-ofb"; #ifdef HAVE_OPENSSL_AES_CTR list += "aes256-ctr"; #endif #ifdef HAVE_OPENSSL_AES_GCM list += "aes256-gcm"; #endif #ifdef HAVE_OPENSSL_AES_CCM list += "aes256-ccm"; #endif list += "blowfish-ecb"; list += "blowfish-cbc-pkcs7"; list += "blowfish-cbc"; list += "blowfish-cfb"; list += "blowfish-ofb"; list += "tripledes-ecb"; list += "tripledes-cbc"; list += "des-ecb"; list += "des-ecb-pkcs7"; list += "des-cbc"; list += "des-cbc-pkcs7"; list += "des-cfb"; list += "des-ofb"; list += "cast5-ecb"; list += "cast5-cbc"; list += "cast5-cbc-pkcs7"; list += "cast5-cfb"; list += "cast5-ofb"; return list; } static QStringList all_mac_types() { QStringList list; list += "hmac(md5)"; list += "hmac(sha1)"; #ifdef SHA224_DIGEST_LENGTH list += "hmac(sha224)"; #endif #ifdef SHA256_DIGEST_LENGTH list += "hmac(sha256)"; #endif #ifdef SHA384_DIGEST_LENGTH list += "hmac(sha384)"; #endif #ifdef SHA512_DIGEST_LENGTH list += "hmac(sha512)"; #endif list += "hmac(ripemd160)"; return list; } class opensslInfoContext : public InfoContext { Q_OBJECT public: opensslInfoContext(Provider *p) : InfoContext(p) { } Provider::Context *clone() const { return new opensslInfoContext(*this); } QStringList supportedHashTypes() const { return all_hash_types(); } QStringList supportedCipherTypes() const { return all_cipher_types(); } QStringList supportedMACTypes() const { return all_mac_types(); } }; class opensslRandomContext : public RandomContext { public: opensslRandomContext(QCA::Provider *p) : RandomContext(p) { } Context *clone() const { return new opensslRandomContext(*this); } QCA::SecureArray nextBytes(int size) { QCA::SecureArray buf(size); int r; // FIXME: loop while we don't have enough random bytes. while (true) { r = RAND_bytes((unsigned char*)(buf.data()), size); if (r == 1) break; // success } return buf; } }; } using namespace opensslQCAPlugin; class opensslProvider : public Provider { public: bool openssl_initted; opensslProvider() { openssl_initted = false; } void init() { OpenSSL_add_all_algorithms(); ERR_load_crypto_strings(); // seed the RNG if it's not seeded yet if (RAND_status() == 0) { qsrand(time(NULL)); char buf[128]; for(int n = 0; n < 128; ++n) buf[n] = qrand(); RAND_seed(buf, 128); } openssl_initted = true; } ~opensslProvider() { // FIXME: ? for now we never deinit, in case other libs/code // are using openssl /*if(!openssl_initted) return; // todo: any other shutdown? EVP_cleanup(); //ENGINE_cleanup(); CRYPTO_cleanup_all_ex_data(); ERR_remove_state(0); ERR_free_strings();*/ } int qcaVersion() const { return QCA_VERSION; } QString name() const { return "qca-ossl"; } QString credit() const { return QString( "This product includes cryptographic software " "written by Eric Young (eay@cryptsoft.com)"); } QStringList features() const { QStringList list; list += "random"; list += all_hash_types(); list += all_mac_types(); list += all_cipher_types(); #ifdef HAVE_OPENSSL_MD2 list += "pbkdf1(md2)"; #endif list += "pbkdf1(sha1)"; list += "pbkdf2(sha1)"; + list += "hkdf(sha256)"; list += "pkey"; list += "dlgroup"; list += "rsa"; list += "dsa"; list += "dh"; list += "cert"; list += "csr"; list += "crl"; list += "certcollection"; list += "pkcs12"; list += "tls"; list += "cms"; list += "ca"; return list; } Context *createContext(const QString &type) { //OpenSSL_add_all_digests(); if ( type == "random" ) return new opensslRandomContext(this); else if ( type == "info" ) return new opensslInfoContext(this); else if ( type == "sha1" ) return new opensslHashContext( EVP_sha1(), this, type); #ifdef HAVE_OPENSSL_SHA0 else if ( type == "sha0" ) return new opensslHashContext( EVP_sha(), this, type); #endif else if ( type == "ripemd160" ) return new opensslHashContext( EVP_ripemd160(), this, type); #ifdef HAVE_OPENSSL_MD2 else if ( type == "md2" ) return new opensslHashContext( EVP_md2(), this, type); #endif else if ( type == "md4" ) return new opensslHashContext( EVP_md4(), this, type); else if ( type == "md5" ) return new opensslHashContext( EVP_md5(), this, type); #ifdef SHA224_DIGEST_LENGTH else if ( type == "sha224" ) return new opensslHashContext( EVP_sha224(), this, type); #endif #ifdef SHA256_DIGEST_LENGTH else if ( type == "sha256" ) return new opensslHashContext( EVP_sha256(), this, type); #endif #ifdef SHA384_DIGEST_LENGTH else if ( type == "sha384" ) return new opensslHashContext( EVP_sha384(), this, type); #endif #ifdef SHA512_DIGEST_LENGTH else if ( type == "sha512" ) return new opensslHashContext( EVP_sha512(), this, type); #endif /* #ifdef OBJ_whirlpool else if ( type == "whirlpool" ) return new opensslHashContext( EVP_whirlpool(), this, type); #endif */ else if ( type == "pbkdf1(sha1)" ) return new opensslPbkdf1Context( EVP_sha1(), this, type ); #ifdef HAVE_OPENSSL_MD2 else if ( type == "pbkdf1(md2)" ) return new opensslPbkdf1Context( EVP_md2(), this, type ); #endif else if ( type == "pbkdf2(sha1)" ) return new opensslPbkdf2Context( this, type ); + else if ( type == "hkdf(sha256)" ) + return new opensslHkdfContext( this, type ); else if ( type == "hmac(md5)" ) return new opensslHMACContext( EVP_md5(), this, type ); else if ( type == "hmac(sha1)" ) return new opensslHMACContext( EVP_sha1(),this, type ); #ifdef SHA224_DIGEST_LENGTH else if ( type == "hmac(sha224)" ) return new opensslHMACContext( EVP_sha224(), this, type); #endif #ifdef SHA256_DIGEST_LENGTH else if ( type == "hmac(sha256)" ) return new opensslHMACContext( EVP_sha256(), this, type); #endif #ifdef SHA384_DIGEST_LENGTH else if ( type == "hmac(sha384)" ) return new opensslHMACContext( EVP_sha384(), this, type); #endif #ifdef SHA512_DIGEST_LENGTH else if ( type == "hmac(sha512)" ) return new opensslHMACContext( EVP_sha512(), this, type); #endif else if ( type == "hmac(ripemd160)" ) return new opensslHMACContext( EVP_ripemd160(), this, type ); else if ( type == "aes128-ecb" ) return new opensslCipherContext( EVP_aes_128_ecb(), 0, this, type); else if ( type == "aes128-cfb" ) return new opensslCipherContext( EVP_aes_128_cfb(), 0, this, type); else if ( type == "aes128-cbc" ) return new opensslCipherContext( EVP_aes_128_cbc(), 0, this, type); else if ( type == "aes128-cbc-pkcs7" ) return new opensslCipherContext( EVP_aes_128_cbc(), 1, this, type); else if ( type == "aes128-ofb" ) return new opensslCipherContext( EVP_aes_128_ofb(), 0, this, type); #ifdef HAVE_OPENSSL_AES_CTR else if ( type == "aes128-ctr" ) return new opensslCipherContext( EVP_aes_128_ctr(), 0, this, type); #endif #ifdef HAVE_OPENSSL_AES_GCM else if ( type == "aes128-gcm" ) return new opensslCipherContext( EVP_aes_128_gcm(), 0, this, type); #endif #ifdef HAVE_OPENSSL_AES_CCM else if ( type == "aes128-ccm" ) return new opensslCipherContext( EVP_aes_128_ccm(), 0, this, type); #endif else if ( type == "aes192-ecb" ) return new opensslCipherContext( EVP_aes_192_ecb(), 0, this, type); else if ( type == "aes192-cfb" ) return new opensslCipherContext( EVP_aes_192_cfb(), 0, this, type); else if ( type == "aes192-cbc" ) return new opensslCipherContext( EVP_aes_192_cbc(), 0, this, type); else if ( type == "aes192-cbc-pkcs7" ) return new opensslCipherContext( EVP_aes_192_cbc(), 1, this, type); else if ( type == "aes192-ofb" ) return new opensslCipherContext( EVP_aes_192_ofb(), 0, this, type); #ifdef HAVE_OPENSSL_AES_CTR else if ( type == "aes192-ctr" ) return new opensslCipherContext( EVP_aes_192_ctr(), 0, this, type); #endif #ifdef HAVE_OPENSSL_AES_GCM else if ( type == "aes192-gcm" ) return new opensslCipherContext( EVP_aes_192_gcm(), 0, this, type); #endif #ifdef HAVE_OPENSSL_AES_CCM else if ( type == "aes192-ccm" ) return new opensslCipherContext( EVP_aes_192_ccm(), 0, this, type); #endif else if ( type == "aes256-ecb" ) return new opensslCipherContext( EVP_aes_256_ecb(), 0, this, type); else if ( type == "aes256-cfb" ) return new opensslCipherContext( EVP_aes_256_cfb(), 0, this, type); else if ( type == "aes256-cbc" ) return new opensslCipherContext( EVP_aes_256_cbc(), 0, this, type); else if ( type == "aes256-cbc-pkcs7" ) return new opensslCipherContext( EVP_aes_256_cbc(), 1, this, type); else if ( type == "aes256-ofb" ) return new opensslCipherContext( EVP_aes_256_ofb(), 0, this, type); #ifdef HAVE_OPENSSL_AES_CTR else if ( type == "aes256-ctr" ) return new opensslCipherContext( EVP_aes_256_ctr(), 0, this, type); #endif #ifdef HAVE_OPENSSL_AES_GCM else if ( type == "aes256-gcm" ) return new opensslCipherContext( EVP_aes_256_gcm(), 0, this, type); #endif #ifdef HAVE_OPENSSL_AES_CCM else if ( type == "aes256-ccm" ) return new opensslCipherContext( EVP_aes_256_ccm(), 0, this, type); #endif else if ( type == "blowfish-ecb" ) return new opensslCipherContext( EVP_bf_ecb(), 0, this, type); else if ( type == "blowfish-cfb" ) return new opensslCipherContext( EVP_bf_cfb(), 0, this, type); else if ( type == "blowfish-ofb" ) return new opensslCipherContext( EVP_bf_ofb(), 0, this, type); else if ( type == "blowfish-cbc" ) return new opensslCipherContext( EVP_bf_cbc(), 0, this, type); else if ( type == "blowfish-cbc-pkcs7" ) return new opensslCipherContext( EVP_bf_cbc(), 1, this, type); else if ( type == "tripledes-ecb" ) return new opensslCipherContext( EVP_des_ede3(), 0, this, type); else if ( type == "tripledes-cbc" ) return new opensslCipherContext( EVP_des_ede3_cbc(), 0, this, type); else if ( type == "des-ecb" ) return new opensslCipherContext( EVP_des_ecb(), 0, this, type); else if ( type == "des-ecb-pkcs7" ) return new opensslCipherContext( EVP_des_ecb(), 1, this, type); else if ( type == "des-cbc" ) return new opensslCipherContext( EVP_des_cbc(), 0, this, type); else if ( type == "des-cbc-pkcs7" ) return new opensslCipherContext( EVP_des_cbc(), 1, this, type); else if ( type == "des-cfb" ) return new opensslCipherContext( EVP_des_cfb(), 0, this, type); else if ( type == "des-ofb" ) return new opensslCipherContext( EVP_des_ofb(), 0, this, type); else if ( type == "cast5-ecb" ) return new opensslCipherContext( EVP_cast5_ecb(), 0, this, type); else if ( type == "cast5-cbc" ) return new opensslCipherContext( EVP_cast5_cbc(), 0, this, type); else if ( type == "cast5-cbc-pkcs7" ) return new opensslCipherContext( EVP_cast5_cbc(), 1, this, type); else if ( type == "cast5-cfb" ) return new opensslCipherContext( EVP_cast5_cfb(), 0, this, type); else if ( type == "cast5-ofb" ) return new opensslCipherContext( EVP_cast5_ofb(), 0, this, type); else if ( type == "pkey" ) return new MyPKeyContext( this ); else if ( type == "dlgroup" ) return new MyDLGroup( this ); else if ( type == "rsa" ) return new RSAKey( this ); else if ( type == "dsa" ) return new DSAKey( this ); else if ( type == "dh" ) return new DHKey( this ); else if ( type == "cert" ) return new MyCertContext( this ); else if ( type == "csr" ) return new MyCSRContext( this ); else if ( type == "crl" ) return new MyCRLContext( this ); else if ( type == "certcollection" ) return new MyCertCollectionContext( this ); else if ( type == "pkcs12" ) return new MyPKCS12Context( this ); else if ( type == "tls" ) return new MyTLSContext( this ); else if ( type == "cms" ) return new CMSContext( this ); else if ( type == "ca" ) return new MyCAContext( this ); return 0; } }; class opensslPlugin : public QObject, public QCAPlugin { Q_OBJECT #if QT_VERSION >= 0x050000 Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0") #endif Q_INTERFACES(QCAPlugin) public: virtual Provider *createProvider() { return new opensslProvider; } }; #include "qca-ossl.moc" #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(qca_ossl, opensslPlugin) #endif diff --git a/src/qca_basic.cpp b/src/qca_basic.cpp index c2e10e1c..395ae8b0 100644 --- a/src/qca_basic.cpp +++ b/src/qca_basic.cpp @@ -1,594 +1,625 @@ /* * Copyright (C) 2003-2007 Justin Karneges * Copyright (C) 2004,2005,2007 Brad Hards * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include "qca_basic.h" #include "qcaprovider.h" #include #include namespace QCA { // from qca_core.cpp QMutex *global_random_mutex(); Random *global_random(); Provider::Context *getContext(const QString &type, Provider *p); // from qca_publickey.cpp ProviderList allProviders(); Provider *providerForName(const QString &name); static void mergeList(QStringList *a, const QStringList &b) { foreach(const QString &s, b) { if(!a->contains(s)) a->append(s); } } static QStringList get_hash_types(Provider *p) { QStringList out; InfoContext *c = static_cast(getContext("info", p)); if(!c) return out; out = c->supportedHashTypes(); delete c; return out; } static QStringList get_cipher_types(Provider *p) { QStringList out; InfoContext *c = static_cast(getContext("info", p)); if(!c) return out; out = c->supportedCipherTypes(); delete c; return out; } static QStringList get_mac_types(Provider *p) { QStringList out; InfoContext *c = static_cast(getContext("info", p)); if(!c) return out; out = c->supportedMACTypes(); delete c; return out; } static QStringList get_types(QStringList (*get_func)(Provider *p), const QString &provider) { QStringList out; if(!provider.isEmpty()) { Provider *p = providerForName(provider); if(p) out = get_func(p); } else { ProviderList pl = allProviders(); foreach(Provider *p, pl) mergeList(&out, get_func(p)); } return out; } static QStringList supportedHashTypes(const QString &provider) { return get_types(get_hash_types, provider); } static QStringList supportedCipherTypes(const QString &provider) { return get_types(get_cipher_types, provider); } static QStringList supportedMACTypes(const QString &provider) { return get_types(get_mac_types, provider); } //---------------------------------------------------------------------------- // Random //---------------------------------------------------------------------------- Random::Random(const QString &provider) :Algorithm("random", provider) { } Random::Random(const Random &from) :Algorithm(from) { } Random::~Random() { } Random & Random::operator=(const Random &from) { Algorithm::operator=(from); return *this; } uchar Random::nextByte() { return (uchar)(nextBytes(1)[0]); } SecureArray Random::nextBytes(int size) { return static_cast(context())->nextBytes(size); } uchar Random::randomChar() { QMutexLocker locker(global_random_mutex()); return global_random()->nextByte(); } int Random::randomInt() { QMutexLocker locker(global_random_mutex()); SecureArray a = global_random()->nextBytes(sizeof(int)); int x; memcpy(&x, a.data(), a.size()); return x; } SecureArray Random::randomArray(int size) { QMutexLocker locker(global_random_mutex()); return global_random()->nextBytes(size); } //---------------------------------------------------------------------------- // Hash //---------------------------------------------------------------------------- Hash::Hash(const QString &type, const QString &provider) :Algorithm(type, provider) { } Hash::Hash(const Hash &from) :Algorithm(from), BufferedComputation(from) { } Hash::~Hash() { } Hash & Hash::operator=(const Hash &from) { Algorithm::operator=(from); return *this; } QStringList Hash::supportedTypes(const QString &provider) { return supportedHashTypes(provider); } QString Hash::type() const { // algorithm type is the same as the hash type return Algorithm::type(); } void Hash::clear() { static_cast(context())->clear(); } void Hash::update(const MemoryRegion &a) { static_cast(context())->update(a); } void Hash::update(const QByteArray &a) { update(MemoryRegion(a)); } void Hash::update(const char *data, int len) { if(len < 0) len = qstrlen(data); if(len == 0) return; update(MemoryRegion(QByteArray::fromRawData(data, len))); } // Reworked from KMD5, from KDE's kdelibs void Hash::update(QIODevice *file) { char buffer[1024]; int len; while ((len=file->read(reinterpret_cast(buffer), sizeof(buffer))) > 0) update(buffer, len); } MemoryRegion Hash::final() { return static_cast(context())->final(); } MemoryRegion Hash::hash(const MemoryRegion &a) { return process(a); } QString Hash::hashToString(const MemoryRegion &a) { return arrayToHex(hash(a).toByteArray()); } //---------------------------------------------------------------------------- // Cipher //---------------------------------------------------------------------------- class Cipher::Private { public: QString type; Cipher::Mode mode; Cipher::Padding pad; Direction dir; SymmetricKey key; InitializationVector iv; AuthTag tag; bool ok, done; }; Cipher::Cipher(const QString &type, Mode mode, Padding pad, Direction dir, const SymmetricKey &key, const InitializationVector &iv, const QString &provider) :Algorithm(withAlgorithms(type, mode, pad), provider) { d = new Private; d->type = type; d->mode = mode; d->pad = pad; if(!key.isEmpty()) setup(dir, key, iv); } Cipher::Cipher(const QString &type, Cipher::Mode mode, Cipher::Padding pad, Direction dir, const SymmetricKey &key, const InitializationVector &iv, const AuthTag &tag, const QString &provider) : Algorithm(withAlgorithms(type, mode, pad), provider) { d = new Private; d->type = type; d->mode = mode; d->pad = pad; d->tag = tag; if(!key.isEmpty()) setup(dir, key, iv, tag); } Cipher::Cipher(const Cipher &from) :Algorithm(from), Filter(from) { d = new Private(*from.d); } Cipher::~Cipher() { delete d; } Cipher & Cipher::operator=(const Cipher &from) { Algorithm::operator=(from); *d = *from.d; return *this; } QStringList Cipher::supportedTypes(const QString &provider) { return supportedCipherTypes(provider); } QString Cipher::type() const { return d->type; } Cipher::Mode Cipher::mode() const { return d->mode; } Cipher::Padding Cipher::padding() const { return d->pad; } Direction Cipher::direction() const { return d->dir; } KeyLength Cipher::keyLength() const { return static_cast(context())->keyLength(); } bool Cipher::validKeyLength(int n) const { KeyLength len = keyLength(); return ((n >= len.minimum()) && (n <= len.maximum()) && (n % len.multiple() == 0)); } int Cipher::blockSize() const { return static_cast(context())->blockSize(); } AuthTag Cipher::tag() const { return static_cast(context())->tag(); } void Cipher::clear() { d->done = false; static_cast(context())->setup(d->dir, d->key, d->iv, d->tag); } MemoryRegion Cipher::update(const MemoryRegion &a) { SecureArray out; if(d->done) return out; d->ok = static_cast(context())->update(a, &out); return out; } MemoryRegion Cipher::final() { SecureArray out; if(d->done) return out; d->done = true; d->ok = static_cast(context())->final(&out); return out; } bool Cipher::ok() const { return d->ok; } void Cipher::setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv) { setup(dir, key, iv, AuthTag()); } void Cipher::setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv, const AuthTag &tag) { d->dir = dir; d->key = key; d->iv = iv; d->tag = tag; clear(); } QString Cipher::withAlgorithms(const QString &cipherType, Mode modeType, Padding paddingType) { QString mode; switch(modeType) { case CBC: mode = "cbc"; break; case CFB: mode = "cfb"; break; case OFB: mode = "ofb"; break; case ECB: mode = "ecb"; break; case CTR: mode = "ctr"; break; case GCM: mode = "gcm"; break; case CCM: mode = "ccm"; break; default: Q_ASSERT(0); } // do the default if(paddingType == DefaultPadding) { // logic from Botan if(modeType == CBC) paddingType = PKCS7; else paddingType = NoPadding; } QString pad; if(paddingType == NoPadding) pad = ""; else pad = "pkcs7"; QString result = cipherType + '-' + mode; if(!pad.isEmpty()) result += QString("-") + pad; return result; } //---------------------------------------------------------------------------- // MessageAuthenticationCode //---------------------------------------------------------------------------- class MessageAuthenticationCode::Private { public: SymmetricKey key; bool done; MemoryRegion buf; }; MessageAuthenticationCode::MessageAuthenticationCode(const QString &type, const SymmetricKey &key, const QString &provider) :Algorithm(type, provider) { d = new Private; setup(key); } MessageAuthenticationCode::MessageAuthenticationCode(const MessageAuthenticationCode &from) :Algorithm(from), BufferedComputation(from) { d = new Private(*from.d); } MessageAuthenticationCode::~MessageAuthenticationCode() { delete d; } MessageAuthenticationCode & MessageAuthenticationCode::operator=(const MessageAuthenticationCode &from) { Algorithm::operator=(from); *d = *from.d; return *this; } QStringList MessageAuthenticationCode::supportedTypes(const QString &provider) { return supportedMACTypes(provider); } QString MessageAuthenticationCode::type() const { // algorithm type is the same as the mac type return Algorithm::type(); } KeyLength MessageAuthenticationCode::keyLength() const { return static_cast(context())->keyLength(); } bool MessageAuthenticationCode::validKeyLength(int n) const { KeyLength len = keyLength(); return ((n >= len.minimum()) && (n <= len.maximum()) && (n % len.multiple() == 0)); } void MessageAuthenticationCode::clear() { d->done = false; static_cast(context())->setup(d->key); } void MessageAuthenticationCode::update(const MemoryRegion &a) { if(d->done) return; static_cast(context())->update(a); } MemoryRegion MessageAuthenticationCode::final() { if(!d->done) { d->done = true; static_cast(context())->final(&d->buf); } return d->buf; } void MessageAuthenticationCode::setup(const SymmetricKey &key) { d->key = key; clear(); } //---------------------------------------------------------------------------- // Key Derivation Function //---------------------------------------------------------------------------- KeyDerivationFunction::KeyDerivationFunction(const QString &type, const QString &provider) :Algorithm(type, provider) { } KeyDerivationFunction::KeyDerivationFunction(const KeyDerivationFunction &from) :Algorithm(from) { } KeyDerivationFunction::~KeyDerivationFunction() { } KeyDerivationFunction & KeyDerivationFunction::operator=(const KeyDerivationFunction &from) { Algorithm::operator=(from); return *this; } SymmetricKey KeyDerivationFunction::makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, unsigned int iterationCount) { return static_cast(context())->makeKey(secret, salt, keyLength, iterationCount); } SymmetricKey KeyDerivationFunction::makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, int msecInterval, unsigned int *iterationCount) { return static_cast(context())->makeKey(secret, salt, keyLength, msecInterval, iterationCount); } QString KeyDerivationFunction::withAlgorithm(const QString &kdfType, const QString &algType) { return (kdfType + '(' + algType + ')'); } +//---------------------------------------------------------------------------- +// HKDF +//---------------------------------------------------------------------------- +HKDF::HKDF(const QString &algorithm, const QString &provider) +: Algorithm(QStringLiteral("hkdf(") + algorithm + ')', provider) +{ +} + +HKDF::HKDF(const HKDF &from) +: Algorithm(from) +{ +} + +HKDF::~HKDF() +{ +} + +HKDF & HKDF::operator=(const HKDF &from) +{ + Algorithm::operator=(from); + return *this; +} + +SymmetricKey HKDF::makeKey(const SecureArray &secret, const InitializationVector &salt, const InitializationVector &info, unsigned int keyLength) +{ + return static_cast(context())->makeKey(secret, + salt, + info, + keyLength); +} + } diff --git a/unittest/kdfunittest/kdfunittest.cpp b/unittest/kdfunittest/kdfunittest.cpp index ed94fbaa..4683f6af 100644 --- a/unittest/kdfunittest/kdfunittest.cpp +++ b/unittest/kdfunittest/kdfunittest.cpp @@ -1,481 +1,536 @@ /** * Copyright (C) 2004-2006 Brad Hards * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef QT_STATICPLUGIN #include "import_plugins.h" #endif class KDFUnitTest : public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void pbkdf1md2Tests_data(); void pbkdf1md2Tests(); void pbkdf1sha1Tests_data(); void pbkdf1sha1Tests(); void pbkdf1sha1TimeTest(); void pbkdf2Tests_data(); void pbkdf2Tests(); void pbkdf2TimeTest(); void pbkdf2extraTests(); + void hkdfTests_data(); + void hkdfTests(); private: QCA::Initializer* m_init; }; void KDFUnitTest::initTestCase() { m_init = new QCA::Initializer; } void KDFUnitTest::cleanupTestCase() { delete m_init; } void KDFUnitTest::pbkdf1md2Tests_data() { QTest::addColumn("secret"); // usually a password or passphrase QTest::addColumn("output"); // the key you get back QTest::addColumn("salt"); // a salt or initialisation vector QTest::addColumn("outputLength"); // if the algo supports variable length keys, len QTest::addColumn("iterationCount"); // number of iterations // These are from Botan's test suite QTest::newRow("1") << QString("71616c7a73656774") << QString("7c1991f3f38a09d70cf3b1acadb70bc6") << QString("40cf117c3865e0cf") << static_cast(16) << static_cast(1000); QTest::newRow("2") << QString("766e68617a6a66736978626f6d787175") << QString("677500eda9f0c5e96e0a11f90fb9") << QString("3a2484ce5d3e1b4d") << static_cast(14) << static_cast(1); QTest::newRow("3") << QString("66686565746e657162646d7171716e797977696f716a666c6f6976636371756a") << QString("91a5b689156b441bf27dd2bdd276") << QString("5d838b0f4fa22bfa2157f9083d87f8752e0495bb2113012761ef11b66e87c3cb") << static_cast(14) << static_cast(15); QTest::newRow("4") << QString("736e6279696e6a7075696b7176787867726c6b66") << QString("49516935cc9f438bafa30ff038fb") << QString("f22d341361b47e3390107bd973fdc0d3e0bc02a3") << static_cast(14) << static_cast(2); } void KDFUnitTest::pbkdf1md2Tests() { QStringList providersToTest; providersToTest.append("qca-ossl"); // gcrypt doesn't do md2... // providersToTest.append("qca-gcrypt"); providersToTest.append("qca-botan"); QFETCH(QString, secret); QFETCH(QString, output); QFETCH(QString, salt); QFETCH(unsigned int, outputLength); QFETCH(unsigned int, iterationCount); foreach(QString provider, providersToTest) { if(!QCA::isSupported("pbkdf1(md2)", provider)) QWARN(QString("PBKDF version 1 with MD2 not supported for "+provider).toLocal8Bit()); else { QCA::SecureArray password = QCA::hexToArray( secret ); QCA::InitializationVector iv( QCA::hexToArray( salt) ); QCA::SymmetricKey key = QCA::PBKDF1("md2", provider).makeKey( password, iv, outputLength, iterationCount); QCOMPARE( QCA::arrayToHex( key.toByteArray() ), output ); } } } void KDFUnitTest::pbkdf1sha1Tests_data() { QTest::addColumn("secret"); // usually a password or passphrase QTest::addColumn("output"); // the key you get back QTest::addColumn("salt"); // a salt or initialisation vector QTest::addColumn("outputLength"); // if the algo supports variable length keys, len QTest::addColumn("iterationCount"); // number of iterations // These are from Botan's test suite QTest::newRow("1") << QString("66746c6b6662786474626a62766c6c7662776977") << QString("768b277dc970f912dbdd3edad48ad2f065d25d") << QString("40ac5837560251c275af5e30a6a3074e57ced38e") << static_cast(19) << static_cast(6); QTest::newRow("2") << QString("786e736f736d6b766867677a7370636e63706f63") << QString("4d90e846a4b6aaa02ac548014a00e97e506b2afb") << QString("7008a9dc1b9a81470a2360275c19dab77f716824") << static_cast(20) << static_cast(6); QTest::newRow("3") << QString("6f74696c71776c756b717473") << QString("71ed1a995e693efcd33155935e800037da74ea28") << QString("ccfc44c09339040e55d3f7f76ca6ef838fde928717241deb9ac1a4ef45a27711") << static_cast(20) << static_cast(2001); QTest::newRow("4") << QString("6b7a6e657166666c6274767374686e6663746166") << QString("f345fb8fbd880206b650266661f6") << QString("8108883fc04a01feb10661651516425dad1c93e0") << static_cast(14) << static_cast(10000); QTest::newRow("5") << QString("716b78686c7170656d7868796b6d7975636a626f") << QString("2d54dfed0c7ef7d20b0945ba414a") << QString("bc8bc53d4604977c3adb1d19c15e87b77a84c2f6") << static_cast(14) << static_cast(10000); } void KDFUnitTest::pbkdf1sha1Tests() { QStringList providersToTest; providersToTest.append("qca-ossl"); // providersToTest.append("qca-gcrypt"); providersToTest.append("qca-botan"); QFETCH(QString, secret); QFETCH(QString, output); QFETCH(QString, salt); QFETCH(unsigned int, outputLength); QFETCH(unsigned int, iterationCount); foreach(QString provider, providersToTest) { if(!QCA::isSupported("pbkdf1(sha1)", provider)) QWARN(QString("PBKDF version 1 with SHA1 not supported for "+provider).toLocal8Bit()); else { QCA::SecureArray password = QCA::hexToArray( secret ); QCA::InitializationVector iv( QCA::hexToArray( salt) ); QCA::SymmetricKey key = QCA::PBKDF1("sha1", provider).makeKey( password, iv, outputLength, iterationCount); QCOMPARE( QCA::arrayToHex( key.toByteArray() ), output ); } } } void KDFUnitTest::pbkdf1sha1TimeTest() { QStringList providersToTest; providersToTest.append("qca-ossl"); providersToTest.append("qca-botan"); providersToTest.append("qca-gcrypt"); QCA::SecureArray password("secret"); QCA::InitializationVector iv(QByteArray("salt")); unsigned int outputLength = 20; int timeInterval = 200; unsigned int iterationCount; foreach(QString provider, providersToTest) { if(!QCA::isSupported("pbkdf1(sha1)", provider)) { QString warning("PBKDF version 1 with SHA1 not supported for %1"); QWARN(warning.arg(provider).toStdString().c_str()); } else { QCA::SymmetricKey key1(QCA::PBKDF1("sha1", provider).makeKey(password, iv, outputLength, timeInterval, &iterationCount)); QCA::SymmetricKey key2(QCA::PBKDF1("sha1", provider).makeKey(password, iv, outputLength, iterationCount)); QCOMPARE( key1, key2 ); } } } void KDFUnitTest::pbkdf2Tests_data() { QTest::addColumn("secret"); // usually a password or passphrase QTest::addColumn("output"); // the key you get back QTest::addColumn("salt"); // a salt or initialisation vector QTest::addColumn("outputLength"); // if the algo supports variable length keys, len QTest::addColumn("iterationCount"); // number of iterations // These are from Botan's test suite QTest::newRow("1") << QString("6a79756571677872736367676c707864796b6366") << QString("df6d9d72872404bf73e708cf3b7d") << QString("9b56e55328a4c97a250738f8dba1b992e8a1b508") << static_cast(14) << static_cast(10000); QTest::newRow("2") << QString("61717271737a6e7a76767a67746b73616d6d676f") << QString("fa13f40af1ade2a30f2fffd66fc8a659ef95e6388c1682fc0fe4d15a70109517a32942e39c371440") << QString("57487813cdd2220dfc485d932a2979ee8769ea8b") << static_cast(40) << static_cast(101); QTest::newRow("3") << QString("6c7465786d666579796c6d6c62727379696b6177") << QString("027afadd48f4be8dcc4f") << QString("ed1f39a0a7f3889aaf7e60743b3bc1cc2c738e60") << static_cast(10) << static_cast(1000); QTest::newRow("4") << QString("6378676e7972636772766c6c796c6f6c736a706f") << QString("7c0d009fc91b48cb6d19bafbfccff3e2ccabfe725eaa234e56bde1d551c132f2") << QString("94ac88200743fb0f6ac51be62166cbef08d94c15") << static_cast(32) << static_cast(1); QTest::newRow("5") << QString("7871796668727865686965646c6865776e76626a") << QString("4661301d3517ca4443a6a607b32b2a63f69996299df75db75f1e0b98dd0eb7d8") << QString("24a1a50b17d63ee8394b69fc70887f4f94883d68") << static_cast(32) << static_cast(5); QTest::newRow("6") << QString("616e6461716b706a7761627663666e706e6a6b6c") << QString("82fb44a521448d5aac94b5158ead1e4dcd7363081a747b9f7626752bda2d") << QString("9316c80801623cc2734af74bec42cf4dbaa3f6d5") << static_cast(30) << static_cast(100); QTest::newRow("7") << QString("687361767679766f636c6f79757a746c736e6975") << QString("f8ec2b0ac817896ac8189d787c6424ed24a6d881436687a4629802c0ecce") << QString("612cc61df3cf2bdb36e10c4d8c9d73192bddee05") << static_cast(30) << static_cast(100); QTest::newRow("8") << QString("6561696d72627a70636f706275736171746b6d77") << QString("c9a0b2622f13916036e29e7462e206e8ba5b50ce9212752eb8ea2a4aa7b40a4cc1bf") << QString("45248f9d0cebcb86a18243e76c972a1f3b36772a") << static_cast(34) << static_cast(100); QTest::newRow("9") << QString("67777278707178756d7364736d626d6866686d666463766c63766e677a6b6967") << QString("4c9db7ba24955225d5b845f65ef24ef1b0c6e86f2e39c8ddaa4b8abd26082d1f350381fadeaeb560dc447afc68a6b47e6ea1e7412f6cf7b2d82342fccd11d3b4") << QString("a39b76c6eec8374a11493ad08c246a3e40dfae5064f4ee3489c273646178") << static_cast(64) << static_cast(1000); } void KDFUnitTest::pbkdf2Tests() { QStringList providersToTest; providersToTest.append("qca-ossl"); providersToTest.append("qca-gcrypt"); providersToTest.append("qca-botan"); QFETCH(QString, secret); QFETCH(QString, output); QFETCH(QString, salt); QFETCH(unsigned int, outputLength); QFETCH(unsigned int, iterationCount); foreach(QString provider, providersToTest) { if(!QCA::isSupported("pbkdf2(sha1)", provider)) QWARN(QString("PBKDF version 2 with SHA1 not supported for "+provider).toLocal8Bit()); else { QCA::SecureArray password = QCA::hexToArray( secret ); QCA::InitializationVector iv( QCA::hexToArray( salt) ); QCA::SymmetricKey key = QCA::PBKDF2("sha1", provider).makeKey( password, iv, outputLength, iterationCount); QCOMPARE( QCA::arrayToHex( key.toByteArray() ), output ); } } } void KDFUnitTest::pbkdf2TimeTest() { QStringList providersToTest; providersToTest.append("qca-ossl"); providersToTest.append("qca-botan"); providersToTest.append("qca-gcrypt"); QCA::SecureArray password("secret"); QCA::InitializationVector iv(QByteArray("salt")); unsigned int outputLength = 20; int timeInterval = 200; unsigned int iterationCount; foreach(QString provider, providersToTest) { if(!QCA::isSupported("pbkdf2(sha1)", provider)) { QString warning("PBKDF version 2 with SHA1 not supported for %1"); QWARN(warning.arg(provider).toStdString().c_str()); } else { QCA::SymmetricKey key1(QCA::PBKDF2("sha1", provider).makeKey(password, iv, outputLength, timeInterval, &iterationCount)); QCA::SymmetricKey key2(QCA::PBKDF2("sha1", provider).makeKey(password, iv, outputLength, iterationCount)); QCOMPARE( key1, key2 ); } } } void KDFUnitTest::pbkdf2extraTests() { QStringList providersToTest; // providersToTest.append("qca-ossl"); providersToTest.append("qca-gcrypt"); providersToTest.append("qca-botan"); foreach(QString provider, providersToTest) { if(!QCA::isSupported("pbkdf2(sha1)", provider)) QWARN(QString("PBKDF version 2 with SHA1 not supported for "+provider).toLocal8Bit()); else { // Not sure where this one came from... { QCA::InitializationVector salt(QCA::SecureArray("what do ya want for nothing?")); QCA::SecureArray password("Jefe"); int iterations = 1000; QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 16, iterations); QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "6349e09cb6b8c1485cfa9780ee3264df" ) ); } // RFC3962, Appendix B { QCA::InitializationVector salt(QCA::SecureArray("ATHENA.MIT.EDUraeburn")); QCA::SecureArray password("password"); int iterations = 1; QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 16, iterations); QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "cdedb5281bb2f801565a1122b2563515" ) ); passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 32, iterations); QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "cdedb5281bb2f801565a1122b25635150ad1f7a04bb9f3a333ecc0e2e1f70837" ) ); } // RFC3962, Appendix B { QCA::InitializationVector salt(QCA::SecureArray("ATHENA.MIT.EDUraeburn")); QCA::SecureArray password("password"); int iterations = 2; QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 16, iterations); QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "01dbee7f4a9e243e988b62c73cda935d" ) ); passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 32, iterations); QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "01dbee7f4a9e243e988b62c73cda935da05378b93244ec8f48a99e61ad799d86" ) ); } // RFC3962, Appendix B { QCA::InitializationVector salt(QCA::SecureArray("ATHENA.MIT.EDUraeburn")); QCA::SecureArray password("password"); int iterations = 1200; QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 16, iterations); QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "5c08eb61fdf71e4e4ec3cf6ba1f5512b" ) ); passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 32, iterations); QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "5c08eb61fdf71e4e4ec3cf6ba1f5512ba7e52ddbc5e5142f708a31e2e62b1e13" ) ); } // RFC3211 and RFC3962, Appendix B { QCA::InitializationVector salt(QCA::hexToArray("1234567878563412")); QCA::SecureArray password("password"); int iterations = 5; QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 16, iterations); QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "d1daa78615f287e6a1c8b120d7062a49" ) ); passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 32, iterations); QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "d1daa78615f287e6a1c8b120d7062a493f98d203e6be49a6adf4fa574b6e64ee" ) ); passwordOut = QCA::PBKDF2().makeKey (password, salt, 8, iterations); QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "d1daa78615f287e6" ) ); } // RFC3962, Appendix B { QCA::InitializationVector salt(QCA::SecureArray("pass phrase equals block size")); QCA::SecureArray password("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); int iterations = 1200; QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 16, iterations); QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "139c30c0966bc32ba55fdbf212530ac9" ) ); passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 32, iterations); QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "139c30c0966bc32ba55fdbf212530ac9c5ec59f1a452f5cc9ad940fea0598ed1" ) ); } // RFC3962, Appendix B { try { QCA::InitializationVector salt(QCA::SecureArray("pass phrase exceeds block size")); QCA::SecureArray password("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); int iterations = 1200; QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 16, iterations); QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "9ccad6d468770cd51b10e6a68721be61" ) ); passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 32, iterations); QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "9ccad6d468770cd51b10e6a68721be611a8b4d282601db3b36be9246915ec82a" ) ); } catch(std::exception &) { if (provider == "qca-botan") qDebug() << "You should use a later version of Botan"; else QFAIL("exception"); } } // RFC3962, Appendix B { QCA::InitializationVector salt(QCA::SecureArray("EXAMPLE.COMpianist")); QCA::SecureArray password(QCA::hexToArray("f09d849e")); int iterations = 50; QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 16, iterations); QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "6b9cf26d45455a43a5b8bb276a403b39" ) ); passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 32, iterations); QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "6b9cf26d45455a43a5b8bb276a403b39e7fe37a0c41e02c281ff3069e1e94f52" ) ); } } } } +void KDFUnitTest::hkdfTests_data() +{ + QTest::addColumn("secret"); // usually a password or passphrase + QTest::addColumn("salt"); // a salt or initialisation vector + QTest::addColumn("info"); // an additional info + QTest::addColumn("output"); // the key you get back + + // RFC 5869, Appendix A + QTest::newRow("1") << QString("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b") + << QString("000102030405060708090a0b0c") + << QString("f0f1f2f3f4f5f6f7f8f9") + << QString("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"); + + QTest::newRow("2") << QString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f") + << QString("606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf") + << QString("b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff") + << QString("b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71cc30c58179ec3e87c14c01d5c1f3434f1d87"); + + QTest::newRow("3") << QString("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b") + << QString() + << QString() + << QString("8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8"); +} + +void KDFUnitTest::hkdfTests() +{ + QStringList providersToTest; + providersToTest.append("qca-ossl"); + //providersToTest.append("qca-gcrypt"); + providersToTest.append("qca-botan"); + + QFETCH(QString, secret); + QFETCH(QString, salt); + QFETCH(QString, info); + QFETCH(QString, output); + + foreach(QString provider, providersToTest) { + if(!QCA::isSupported("hkdf(sha256)", provider)) + QWARN(QString("HKDF with SHA256 not supported for "+provider).toLocal8Bit()); + else { + QCA::SecureArray password = QCA::hexToArray( secret ); + QCA::InitializationVector saltv( QCA::hexToArray( salt ) ); + QCA::InitializationVector infov( QCA::hexToArray( info ) ); + QCA::SymmetricKey key = QCA::HKDF("sha256", provider).makeKey( password, + saltv, + infov, + output.size() / 2 ); + QCOMPARE( QCA::arrayToHex( key.toByteArray() ), output ); + + } + } +} + QTEST_MAIN(KDFUnitTest) #include "kdfunittest.moc"