From 6f1299c0b44c969137d28da346fc6539aac20f3b Mon Sep 17 00:00:00 2001 From: Oliver Wolff Date: Fri, 8 Aug 2014 17:30:19 +0300 Subject: SSL: split ssl files into general and "_openssl" implementation In order to prepare the addition of WinRT and iOS (SecureTransport) implementations of SSL the structure of some SSL files has to be redone. Parts of certificate that probably can be reused by other ports stayed in qsslcertificate.cpp while other parts were moved to qsslcertificate_openssl.cpp. qsslcontext, qsslkey and qsslsocket were suffixed by _openssl to show that these are pure openssl implementations. Change-Id: I7b022dec49759f882274999c0991bf95788f2a3a Reviewed-by: Andrew Knight Reviewed-by: Oliver Wolff Reviewed-by: Richard J. Moore --- src/network/access/qhttpnetworkconnection_p.h | 4 +- src/network/ssl/qsslcertificate.cpp | 716 ++------------------------ src/network/ssl/qsslcertificate_openssl.cpp | 699 +++++++++++++++++++++++++ src/network/ssl/qsslcertificate_p.h | 19 +- src/network/ssl/qsslcontext.cpp | 465 ----------------- src/network/ssl/qsslcontext_openssl.cpp | 465 +++++++++++++++++ src/network/ssl/qsslcontext_openssl_p.h | 113 ++++ src/network/ssl/qsslcontext_p.h | 113 ---- src/network/ssl/qsslkey.cpp | 537 ------------------- src/network/ssl/qsslkey_openssl.cpp | 218 ++++++++ src/network/ssl/qsslkey_p.cpp | 396 ++++++++++++++ src/network/ssl/qsslkey_p.h | 18 +- src/network/ssl/qsslsocket.cpp | 4 +- src/network/ssl/qsslsocket_p.h | 4 +- src/network/ssl/ssl.pri | 13 +- 15 files changed, 1992 insertions(+), 1792 deletions(-) create mode 100644 src/network/ssl/qsslcertificate_openssl.cpp delete mode 100644 src/network/ssl/qsslcontext.cpp create mode 100644 src/network/ssl/qsslcontext_openssl.cpp create mode 100644 src/network/ssl/qsslcontext_openssl_p.h delete mode 100644 src/network/ssl/qsslcontext_p.h delete mode 100644 src/network/ssl/qsslkey.cpp create mode 100644 src/network/ssl/qsslkey_openssl.cpp create mode 100644 src/network/ssl/qsslkey_p.cpp (limited to 'src/network') diff --git a/src/network/access/qhttpnetworkconnection_p.h b/src/network/access/qhttpnetworkconnection_p.h index 42114ae9d6..a96f67485f 100644 --- a/src/network/access/qhttpnetworkconnection_p.h +++ b/src/network/access/qhttpnetworkconnection_p.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtNetwork module of the Qt Toolkit. @@ -73,7 +73,7 @@ #ifndef QT_NO_HTTP #ifndef QT_NO_SSL -# include +# include # include # include # include diff --git a/src/network/ssl/qsslcertificate.cpp b/src/network/ssl/qsslcertificate.cpp index 4b71f34b3a..d5d568e45d 100644 --- a/src/network/ssl/qsslcertificate.cpp +++ b/src/network/ssl/qsslcertificate.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtNetwork module of the Qt Toolkit. @@ -113,33 +113,20 @@ \value EmailAddress The email address associated with the certificate */ +#ifndef QT_NO_OPENSSL #include "qsslsocket_openssl_symbols_p.h" +#endif + #include "qsslcertificate.h" #include "qsslcertificate_p.h" -#include "qsslkey.h" #include "qsslkey_p.h" -#include "qsslcertificateextension.h" -#include "qsslcertificateextension_p.h" -#include -#include -#include #include #include #include -#include -#include -#include -#include -#include -#include -#include QT_BEGIN_NAMESPACE -// forward declaration -static QMap _q_mapFromX509Name(X509_NAME *name); - /*! Constructs a QSslCertificate by reading \a format encoded data from \a device and using the first certificate found. You can @@ -200,19 +187,11 @@ QSslCertificate &QSslCertificate::operator=(const QSslCertificate &other) */ /*! + \fn bool QSslCertificate::operator==(const QSslCertificate &other) const + Returns \c true if this certificate is the same as \a other; otherwise returns \c false. */ -bool QSslCertificate::operator==(const QSslCertificate &other) const -{ - if (d == other.d) - return true; - if (d->null && other.d->null) - return true; - if (d->x509 && other.d->x509) - return q_X509_cmp(d->x509, other.d->x509) == 0; - return false; -} /*! \fn bool QSslCertificate::operator!=(const QSslCertificate &other) const @@ -222,6 +201,8 @@ bool QSslCertificate::operator==(const QSslCertificate &other) const */ /*! + \fn bool QSslCertificate::isNull() const + Returns \c true if this is a null certificate (i.e., a certificate with no contents); otherwise returns \c false. @@ -229,10 +210,6 @@ bool QSslCertificate::operator==(const QSslCertificate &other) const \sa clear() */ -bool QSslCertificate::isNull() const -{ - return d->null; -} #if QT_DEPRECATED_SINCE(5,0) /*! @@ -265,20 +242,15 @@ bool QSslCertificate::isBlacklisted() const } /*! + \fn bool QSslCertificate::isSelfSigned() const \since 5.4 + Returns \c true if this certificate is self signed; otherwise returns \c false. A certificate is considered self-signed its issuer and subject are identical. */ -bool QSslCertificate::isSelfSigned() const -{ - if (!d->x509) - return false; - - return (q_X509_check_issued(d->x509, d->x509) == X509_V_OK); -} /*! Clears the contents of this certificate, making it a null @@ -294,37 +266,15 @@ void QSslCertificate::clear() } /*! + \fn QByteArray QSslCertificate::version() const Returns the certificate's version string. */ -QByteArray QSslCertificate::version() const -{ - QMutexLocker lock(QMutexPool::globalInstanceGet(d.data())); - if (d->versionString.isEmpty() && d->x509) - d->versionString = - QByteArray::number(qlonglong(q_ASN1_INTEGER_get(d->x509->cert_info->version)) + 1); - - return d->versionString; -} /*! + \fn QByteArray QSslCertificate::serialNumber() const + Returns the certificate's serial number string in hexadecimal format. */ -QByteArray QSslCertificate::serialNumber() const -{ - QMutexLocker lock(QMutexPool::globalInstanceGet(d.data())); - if (d->serialNumberString.isEmpty() && d->x509) { - ASN1_INTEGER *serialNumber = d->x509->cert_info->serialNumber; - QByteArray hexString; - hexString.reserve(serialNumber->length * 3); - for (int a = 0; a < serialNumber->length; ++a) { - hexString += QByteArray::number(serialNumber->data[a], 16).rightJustified(2, '0'); - hexString += ':'; - } - hexString.chop(1); - d->serialNumberString = hexString; - } - return d->serialNumberString; -} /*! Returns a cryptographic digest of this certificate. By default, @@ -336,23 +286,6 @@ QByteArray QSslCertificate::digest(QCryptographicHash::Algorithm algorithm) cons return QCryptographicHash::hash(toDer(), algorithm); } -static QByteArray _q_SubjectInfoToString(QSslCertificate::SubjectInfo info) -{ - QByteArray str; - switch (info) { - case QSslCertificate::Organization: str = QByteArray("O"); break; - case QSslCertificate::CommonName: str = QByteArray("CN"); break; - case QSslCertificate::LocalityName: str = QByteArray("L"); break; - case QSslCertificate::OrganizationalUnitName: str = QByteArray("OU"); break; - case QSslCertificate::CountryName: str = QByteArray("C"); break; - case QSslCertificate::StateOrProvinceName: str = QByteArray("ST"); break; - case QSslCertificate::DistinguishedNameQualifier: str = QByteArray("dnQualifier"); break; - case QSslCertificate::SerialNumber: str = QByteArray("serialNumber"); break; - case QSslCertificate::EmailAddress: str = QByteArray("emailAddress"); break; - } - return str; -} - /*! \fn QString QSslCertificate::issuerInfo(SubjectInfo subject) const @@ -363,37 +296,18 @@ static QByteArray _q_SubjectInfoToString(QSslCertificate::SubjectInfo info) \sa subjectInfo() */ -QStringList QSslCertificate::issuerInfo(SubjectInfo info) const -{ - QMutexLocker lock(QMutexPool::globalInstanceGet(d.data())); - // lazy init - if (d->issuerInfo.isEmpty() && d->x509) - d->issuerInfo = - _q_mapFromX509Name(q_X509_get_issuer_name(d->x509)); - - return d->issuerInfo.values(_q_SubjectInfoToString(info)); -} /*! + \fn QStringList QSslCertificate::issuerInfo(const QByteArray &attribute) const + Returns the issuer information for \a attribute from the certificate, or an empty list if there is no information for \a attribute in the certificate. There can be more than one entry for an attribute. \sa subjectInfo() */ -QStringList QSslCertificate::issuerInfo(const QByteArray &attribute) const -{ - QMutexLocker lock(QMutexPool::globalInstanceGet(d.data())); - // lazy init - if (d->issuerInfo.isEmpty() && d->x509) - d->issuerInfo = - _q_mapFromX509Name(q_X509_get_issuer_name(d->x509)); - - return d->issuerInfo.values(attribute); -} /*! - \fn QString QSslCertificate::subjectInfo(SubjectInfo subject) const Returns the information for the \a subject, or an empty list if @@ -402,36 +316,20 @@ QStringList QSslCertificate::issuerInfo(const QByteArray &attribute) const \sa issuerInfo() */ -QStringList QSslCertificate::subjectInfo(SubjectInfo info) const -{ - QMutexLocker lock(QMutexPool::globalInstanceGet(d.data())); - // lazy init - if (d->subjectInfo.isEmpty() && d->x509) - d->subjectInfo = - _q_mapFromX509Name(q_X509_get_subject_name(d->x509)); - - return d->subjectInfo.values(_q_SubjectInfoToString(info)); -} /*! + \fn QStringList QSslCertificate::subjectInfo(const QByteArray &attribute) const + Returns the subject information for \a attribute, or an empty list if there is no information for \a attribute in the certificate. There can be more than one entry for an attribute. \sa issuerInfo() */ -QStringList QSslCertificate::subjectInfo(const QByteArray &attribute) const -{ - QMutexLocker lock(QMutexPool::globalInstanceGet(d.data())); - // lazy init - if (d->subjectInfo.isEmpty() && d->x509) - d->subjectInfo = - _q_mapFromX509Name(q_X509_get_subject_name(d->x509)); - - return d->subjectInfo.values(attribute); -} /*! + \fn QList QSslCertificate::subjectInfoAttributes() const + \since 5.0 Returns a list of the attributes that have values in the subject information of this certificate. The information associated @@ -441,18 +339,10 @@ QStringList QSslCertificate::subjectInfo(const QByteArray &attribute) const \sa subjectInfo() */ -QList QSslCertificate::subjectInfoAttributes() const -{ - QMutexLocker lock(QMutexPool::globalInstanceGet(d.data())); - // lazy init - if (d->subjectInfo.isEmpty() && d->x509) - d->subjectInfo = - _q_mapFromX509Name(q_X509_get_subject_name(d->x509)); - - return d->subjectInfo.uniqueKeys(); -} /*! + \fn QList QSslCertificate::issuerInfoAttributes() const + \since 5.0 Returns a list of the attributes that have values in the issuer information of this certificate. The information associated @@ -462,16 +352,6 @@ QList QSslCertificate::subjectInfoAttributes() const \sa subjectInfo() */ -QList QSslCertificate::issuerInfoAttributes() const -{ - QMutexLocker lock(QMutexPool::globalInstanceGet(d.data())); - // lazy init - if (d->issuerInfo.isEmpty() && d->x509) - d->issuerInfo = - _q_mapFromX509Name(q_X509_get_issuer_name(d->x509)); - - return d->issuerInfo.uniqueKeys(); -} #if QT_DEPRECATED_SINCE(5,0) /*! @@ -483,6 +363,8 @@ QList QSslCertificate::issuerInfoAttributes() const #endif /*! + \fn QMultiMap QSslCertificate::subjectAlternativeNames() const + Returns the list of alternative subject names for this certificate. The alternative names typically contain host names, optionally with wildcards, that are valid for this @@ -495,63 +377,27 @@ QList QSslCertificate::issuerInfoAttributes() const \sa subjectInfo() */ -QMultiMap QSslCertificate::subjectAlternativeNames() const -{ - QMultiMap result; - - if (!d->x509) - return result; - - STACK_OF(GENERAL_NAME) *altNames = (STACK_OF(GENERAL_NAME)*)q_X509_get_ext_d2i(d->x509, NID_subject_alt_name, 0, 0); - - if (altNames) { - for (int i = 0; i < q_sk_GENERAL_NAME_num(altNames); ++i) { - const GENERAL_NAME *genName = q_sk_GENERAL_NAME_value(altNames, i); - if (genName->type != GEN_DNS && genName->type != GEN_EMAIL) - continue; - - int len = q_ASN1_STRING_length(genName->d.ia5); - if (len < 0 || len >= 8192) { - // broken name - continue; - } - - const char *altNameStr = reinterpret_cast(q_ASN1_STRING_data(genName->d.ia5)); - const QString altName = QString::fromLatin1(altNameStr, len); - if (genName->type == GEN_DNS) - result.insert(QSsl::DnsEntry, altName); - else if (genName->type == GEN_EMAIL) - result.insert(QSsl::EmailEntry, altName); - } - q_sk_pop_free((STACK*)altNames, reinterpret_cast(q_sk_free)); - } - - return result; -} /*! + \fn QDateTime QSslCertificate::effectiveDate() const + Returns the date-time that the certificate becomes valid, or an empty QDateTime if this is a null certificate. \sa expiryDate() */ -QDateTime QSslCertificate::effectiveDate() const -{ - return d->notValidBefore; -} /*! + \fn QDateTime QSslCertificate::expiryDate() const + Returns the date-time that the certificate expires, or an empty QDateTime if this is a null certificate. \sa effectiveDate() */ -QDateTime QSslCertificate::expiryDate() const -{ - return d->notValidAfter; -} /*! + \fn Qt::HANDLE QSslCertificate::handle() const Returns a pointer to the native certificate handle, if there is one, or a null pointer otherwise. @@ -562,298 +408,41 @@ QDateTime QSslCertificate::expiryDate() const non-portable, and its return value may vary from platform to platform or change from minor release to minor release. */ -Qt::HANDLE QSslCertificate::handle() const -{ - return Qt::HANDLE(d->x509); -} /*! + \fn QSslKey QSslCertificate::publicKey() const Returns the certificate subject's public key. */ -QSslKey QSslCertificate::publicKey() const -{ - if (!d->x509) - return QSslKey(); - - QSslKey key; - - key.d->type = QSsl::PublicKey; - X509_PUBKEY *xkey = d->x509->cert_info->key; - EVP_PKEY *pkey = q_X509_PUBKEY_get(xkey); - Q_ASSERT(pkey); - - if (q_EVP_PKEY_type(pkey->type) == EVP_PKEY_RSA) { - key.d->rsa = q_EVP_PKEY_get1_RSA(pkey); - key.d->algorithm = QSsl::Rsa; - key.d->isNull = false; - } else if (q_EVP_PKEY_type(pkey->type) == EVP_PKEY_DSA) { - key.d->dsa = q_EVP_PKEY_get1_DSA(pkey); - key.d->algorithm = QSsl::Dsa; - key.d->isNull = false; - } else if (q_EVP_PKEY_type(pkey->type) == EVP_PKEY_DH) { - // DH unsupported - } else { - // error? - } - - q_EVP_PKEY_free(pkey); - return key; -} - -/* - * Convert unknown extensions to a QVariant. - */ -static QVariant x509UnknownExtensionToValue(X509_EXTENSION *ext) -{ - // Get the extension specific method object if available - // we cast away the const-ness here because some versions of openssl - // don't use const for the parameters in the functions pointers stored - // in the object. - X509V3_EXT_METHOD *meth = const_cast(q_X509V3_EXT_get(ext)); - if (!meth) { - ASN1_OCTET_STRING *value = q_X509_EXTENSION_get_data(ext); - QByteArray result( reinterpret_cast(q_ASN1_STRING_data(value)), - q_ASN1_STRING_length(value)); - return result; - } - - //const unsigned char *data = ext->value->data; - void *ext_internal = q_X509V3_EXT_d2i(ext); - - // If this extension can be converted - if (meth->i2v && ext_internal) { - STACK_OF(CONF_VALUE) *val = meth->i2v(meth, ext_internal, 0); - - QVariantMap map; - QVariantList list; - bool isMap = false; - - for (int j = 0; j < q_SKM_sk_num(CONF_VALUE, val); j++) { - CONF_VALUE *nval = q_SKM_sk_value(CONF_VALUE, val, j); - if (nval->name && nval->value) { - isMap = true; - map[QString::fromUtf8(nval->name)] = QString::fromUtf8(nval->value); - } else if (nval->name) { - list << QString::fromUtf8(nval->name); - } else if (nval->value) { - list << QString::fromUtf8(nval->value); - } - } - - if (isMap) - return map; - else - return list; - } else if (meth->i2s && ext_internal) { - //qDebug() << meth->i2s(meth, ext_internal); - QVariant result(QString::fromUtf8(meth->i2s(meth, ext_internal))); - return result; - } else if (meth->i2r && ext_internal) { - QByteArray result; - - BIO *bio = q_BIO_new(q_BIO_s_mem()); - if (!bio) - return result; - - meth->i2r(meth, ext_internal, bio, 0); - - char *bio_buffer; - long bio_size = q_BIO_get_mem_data(bio, &bio_buffer); - result = QByteArray(bio_buffer, bio_size); - - q_BIO_free(bio); - return result; - } - - return QVariant(); -} - -/* - * Convert extensions to a variant. The naming of the keys of the map are - * taken from RFC 5280, however we decided the capitalisation in the RFC - * was too silly for the real world. - */ -static QVariant x509ExtensionToValue(X509_EXTENSION *ext) -{ - ASN1_OBJECT *obj = q_X509_EXTENSION_get_object(ext); - int nid = q_OBJ_obj2nid(obj); - - switch (nid) { - case NID_basic_constraints: - { - BASIC_CONSTRAINTS *basic = reinterpret_cast(q_X509V3_EXT_d2i(ext)); - - QVariantMap result; - result[QLatin1String("ca")] = basic->ca ? true : false; - if (basic->pathlen) - result[QLatin1String("pathLenConstraint")] = (qlonglong)q_ASN1_INTEGER_get(basic->pathlen); - - q_BASIC_CONSTRAINTS_free(basic); - return result; - } - break; - case NID_info_access: - { - AUTHORITY_INFO_ACCESS *info = reinterpret_cast(q_X509V3_EXT_d2i(ext)); - - QVariantMap result; - for (int i=0; i < q_SKM_sk_num(ACCESS_DESCRIPTION, info); i++) { - ACCESS_DESCRIPTION *ad = q_SKM_sk_value(ACCESS_DESCRIPTION, info, i); - - GENERAL_NAME *name = ad->location; - if (name->type == GEN_URI) { - int len = q_ASN1_STRING_length(name->d.uniformResourceIdentifier); - if (len < 0 || len >= 8192) { - // broken name - continue; - } - - const char *uriStr = reinterpret_cast(q_ASN1_STRING_data(name->d.uniformResourceIdentifier)); - const QString uri = QString::fromUtf8(uriStr, len); - - result[QString::fromUtf8(QSslCertificatePrivate::asn1ObjectName(ad->method))] = uri; - } else { - qWarning() << "Strange location type" << name->type; - } - } - -#if OPENSSL_VERSION_NUMBER >= 0x10000000L - q_sk_pop_free((_STACK*)info, reinterpret_cast(q_sk_free)); -#else - q_sk_pop_free((STACK*)info, reinterpret_cast(q_sk_free)); -#endif - return result; - } - break; - case NID_subject_key_identifier: - { - void *ext_internal = q_X509V3_EXT_d2i(ext); - - // we cast away the const-ness here because some versions of openssl - // don't use const for the parameters in the functions pointers stored - // in the object. - X509V3_EXT_METHOD *meth = const_cast(q_X509V3_EXT_get(ext)); - - return QVariant(QString::fromUtf8(meth->i2s(meth, ext_internal))); - } - break; - case NID_authority_key_identifier: - { - AUTHORITY_KEYID *auth_key = reinterpret_cast(q_X509V3_EXT_d2i(ext)); - - QVariantMap result; - - // keyid - if (auth_key->keyid) { - QByteArray keyid(reinterpret_cast(auth_key->keyid->data), - auth_key->keyid->length); - result[QLatin1String("keyid")] = keyid.toHex(); - } - - // issuer - // TODO: GENERAL_NAMES - - // serial - if (auth_key->serial) - result[QLatin1String("serial")] = (qlonglong)q_ASN1_INTEGER_get(auth_key->serial); - - q_AUTHORITY_KEYID_free(auth_key); - return result; - } - break; - } - - return QVariant(); -} - -QSslCertificateExtension QSslCertificatePrivate::convertExtension(X509_EXTENSION *ext) -{ - QSslCertificateExtension result; - - ASN1_OBJECT *obj = q_X509_EXTENSION_get_object(ext); - QByteArray oid = QSslCertificatePrivate::asn1ObjectId(obj); - QByteArray name = QSslCertificatePrivate::asn1ObjectName(obj); - - result.d->oid = QString::fromUtf8(oid); - result.d->name = QString::fromUtf8(name); - - bool critical = q_X509_EXTENSION_get_critical(ext); - result.d->critical = critical; - - // Lets see if we have custom support for this one - QVariant extensionValue = x509ExtensionToValue(ext); - if (extensionValue.isValid()) { - result.d->value = extensionValue; - result.d->supported = true; - - return result; - } - - extensionValue = x509UnknownExtensionToValue(ext); - if (extensionValue.isValid()) { - result.d->value = extensionValue; - result.d->supported = false; - return result; - } - - return result; -} /*! + \fn QList QSslCertificate::extensions() const + Returns a list containing the X509 extensions of this certificate. \since 5.0 */ -QList QSslCertificate::extensions() const -{ - QList result; - - if (!d->x509) - return result; - - int count = q_X509_get_ext_count(d->x509); - - for (int i=0; i < count; i++) { - X509_EXTENSION *ext = q_X509_get_ext(d->x509, i); - result << QSslCertificatePrivate::convertExtension(ext); - } - - return result; -} /*! + \fn QByteArray QSslCertificate::toPem() const + Returns this certificate converted to a PEM (Base64) encoded representation. */ -QByteArray QSslCertificate::toPem() const -{ - if (!d->x509) - return QByteArray(); - return d->QByteArray_from_X509(d->x509, QSsl::Pem); -} /*! + \fn QByteArray QSslCertificate::toDer() const + Returns this certificate converted to a DER (binary) encoded representation. */ -QByteArray QSslCertificate::toDer() const -{ - if (!d->x509) - return QByteArray(); - return d->QByteArray_from_X509(d->x509, QSsl::Der); -} /*! + \fn QString QSslCertificate::toText() const + Returns this certificate converted to a human-readable text representation. \since 5.0 */ -QString QSslCertificate::toText() const -{ - if (!d->x509) - return QString(); - return d->text_from_X509(d->x509); -} /*! Searches all files in the \a path for certificates encoded in the @@ -999,218 +588,6 @@ bool QSslCertificate::importPKCS12(QIODevice *device, return QSslSocketBackendPrivate::importPKCS12(device, key, certificate, caCertificates, passPhrase); } -void QSslCertificatePrivate::init(const QByteArray &data, QSsl::EncodingFormat format) -{ - if (!data.isEmpty()) { - QList certs = (format == QSsl::Pem) - ? certificatesFromPem(data, 1) - : certificatesFromDer(data, 1); - if (!certs.isEmpty()) { - *this = *certs.first().d; - if (x509) - x509 = q_X509_dup(x509); - } - } -} - -#define BEGINCERTSTRING "-----BEGIN CERTIFICATE-----" -#define ENDCERTSTRING "-----END CERTIFICATE-----" - -// ### refactor against QSsl::pemFromDer() etc. (to avoid redundant implementations) -QByteArray QSslCertificatePrivate::QByteArray_from_X509(X509 *x509, QSsl::EncodingFormat format) -{ - if (!x509) { - qWarning("QSslSocketBackendPrivate::X509_to_QByteArray: null X509"); - return QByteArray(); - } - - // Use i2d_X509 to convert the X509 to an array. - int length = q_i2d_X509(x509, 0); - QByteArray array; - array.resize(length); - char *data = array.data(); - char **dataP = &data; - unsigned char **dataPu = (unsigned char **)dataP; - if (q_i2d_X509(x509, dataPu) < 0) - return QByteArray(); - - if (format == QSsl::Der) - return array; - - // Convert to Base64 - wrap at 64 characters. - array = array.toBase64(); - QByteArray tmp; - for (int i = 0; i <= array.size() - 64; i += 64) { - tmp += QByteArray::fromRawData(array.data() + i, 64); - tmp += '\n'; - } - if (int remainder = array.size() % 64) { - tmp += QByteArray::fromRawData(array.data() + array.size() - remainder, remainder); - tmp += '\n'; - } - - return BEGINCERTSTRING "\n" + tmp + ENDCERTSTRING "\n"; -} - -QString QSslCertificatePrivate::text_from_X509(X509 *x509) -{ - if (!x509) { - qWarning("QSslSocketBackendPrivate::text_from_X509: null X509"); - return QString(); - } - - QByteArray result; - BIO *bio = q_BIO_new(q_BIO_s_mem()); - if (!bio) - return QString(); - - q_X509_print(bio, x509); - - QVarLengthArray data; - int count = q_BIO_read(bio, data.data(), 16384); - if ( count > 0 ) { - result = QByteArray( data.data(), count ); - } - - q_BIO_free(bio); - - return QString::fromLatin1(result); -} - -QByteArray QSslCertificatePrivate::asn1ObjectId(ASN1_OBJECT *object) -{ - char buf[80]; // The openssl docs a buffer length of 80 should be more than enough - q_OBJ_obj2txt(buf, sizeof(buf), object, 1); // the 1 says always use the oid not the long name - - return QByteArray(buf); -} - - -QByteArray QSslCertificatePrivate::asn1ObjectName(ASN1_OBJECT *object) -{ - int nid = q_OBJ_obj2nid(object); - if (nid != NID_undef) - return QByteArray(q_OBJ_nid2sn(nid)); - - return asn1ObjectId(object); -} - -static QMap _q_mapFromX509Name(X509_NAME *name) -{ - QMap info; - for (int i = 0; i < q_X509_NAME_entry_count(name); ++i) { - X509_NAME_ENTRY *e = q_X509_NAME_get_entry(name, i); - - QByteArray name = QSslCertificatePrivate::asn1ObjectName(q_X509_NAME_ENTRY_get_object(e)); - unsigned char *data = 0; - int size = q_ASN1_STRING_to_UTF8(&data, q_X509_NAME_ENTRY_get_data(e)); - info.insertMulti(name, QString::fromUtf8((char*)data, size)); - q_CRYPTO_free(data); - } - - return info; -} - -QSslCertificate QSslCertificatePrivate::QSslCertificate_from_X509(X509 *x509) -{ - QSslCertificate certificate; - if (!x509 || !QSslSocket::supportsSsl()) - return certificate; - - ASN1_TIME *nbef = q_X509_get_notBefore(x509); - ASN1_TIME *naft = q_X509_get_notAfter(x509); - certificate.d->notValidBefore = q_getTimeFromASN1(nbef); - certificate.d->notValidAfter = q_getTimeFromASN1(naft); - certificate.d->null = false; - certificate.d->x509 = q_X509_dup(x509); - - return certificate; -} - -static bool matchLineFeed(const QByteArray &pem, int *offset) -{ - char ch = 0; - - // ignore extra whitespace at the end of the line - while (*offset < pem.size() && (ch = pem.at(*offset)) == ' ') - ++*offset; - - if (ch == '\n') { - *offset += 1; - return true; - } - if (ch == '\r' && pem.size() > (*offset + 1) && pem.at(*offset + 1) == '\n') { - *offset += 2; - return true; - } - return false; -} - -QList QSslCertificatePrivate::certificatesFromPem(const QByteArray &pem, int count) -{ - QList certificates; - QSslSocketPrivate::ensureInitialized(); - - int offset = 0; - while (count == -1 || certificates.size() < count) { - int startPos = pem.indexOf(BEGINCERTSTRING, offset); - if (startPos == -1) - break; - startPos += sizeof(BEGINCERTSTRING) - 1; - if (!matchLineFeed(pem, &startPos)) - break; - - int endPos = pem.indexOf(ENDCERTSTRING, startPos); - if (endPos == -1) - break; - - offset = endPos + sizeof(ENDCERTSTRING) - 1; - if (offset < pem.size() && !matchLineFeed(pem, &offset)) - break; - - QByteArray decoded = QByteArray::fromBase64( - QByteArray::fromRawData(pem.data() + startPos, endPos - startPos)); -#if OPENSSL_VERSION_NUMBER >= 0x00908000L - const unsigned char *data = (const unsigned char *)decoded.data(); -#else - unsigned char *data = (unsigned char *)decoded.data(); -#endif - - if (X509 *x509 = q_d2i_X509(0, &data, decoded.size())) { - certificates << QSslCertificate_from_X509(x509); - q_X509_free(x509); - } - } - - return certificates; -} - -QList QSslCertificatePrivate::certificatesFromDer(const QByteArray &der, int count) -{ - QList certificates; - QSslSocketPrivate::ensureInitialized(); - - -#if OPENSSL_VERSION_NUMBER >= 0x00908000L - const unsigned char *data = (const unsigned char *)der.data(); -#else - unsigned char *data = (unsigned char *)der.data(); -#endif - int size = der.size(); - - while (count == -1 || certificates.size() < count) { - if (X509 *x509 = q_d2i_X509(0, &data, size)) { - certificates << QSslCertificate_from_X509(x509); - q_X509_free(x509); - } else { - break; - } - size -= ((char *)data - der.data()); - } - - return certificates; -} - // These certificates are known to be fraudulent and were created during the comodo // compromise. See http://www.comodo.com/Comodo-Fraud-Incident-2011-03-23.html static const char *certificate_blacklist[] = { @@ -1273,6 +650,25 @@ bool QSslCertificatePrivate::isBlacklisted(const QSslCertificate &certificate) return false; } +QByteArray QSslCertificatePrivate::subjectInfoToString(QSslCertificate::SubjectInfo info) +{ + QByteArray str; + switch (info) { + case QSslCertificate::Organization: str = QByteArray("O"); break; + case QSslCertificate::CommonName: str = QByteArray("CN"); break; + case QSslCertificate::LocalityName: str = QByteArray("L"); break; + case QSslCertificate::OrganizationalUnitName: str = QByteArray("OU"); break; + case QSslCertificate::CountryName: str = QByteArray("C"); break; + case QSslCertificate::StateOrProvinceName: str = QByteArray("ST"); break; + case QSslCertificate::DistinguishedNameQualifier: str = QByteArray("dnQualifier"); break; + case QSslCertificate::SerialNumber: str = QByteArray("serialNumber"); break; + case QSslCertificate::EmailAddress: str = QByteArray("emailAddress"); break; + } + return str; +} + + + #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug debug, const QSslCertificate &certificate) { diff --git a/src/network/ssl/qsslcertificate_openssl.cpp b/src/network/ssl/qsslcertificate_openssl.cpp new file mode 100644 index 0000000000..664f5eba08 --- /dev/null +++ b/src/network/ssl/qsslcertificate_openssl.cpp @@ -0,0 +1,699 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the QtNetwork module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qsslsocket_openssl_symbols_p.h" +#include "qsslcertificate_p.h" +#include "qsslkey_p.h" +#include "qsslcertificateextension_p.h" + +#include + +QT_BEGIN_NAMESPACE + +// forward declaration +static QMap _q_mapFromX509Name(X509_NAME *name); + +bool QSslCertificate::operator==(const QSslCertificate &other) const +{ + if (d == other.d) + return true; + if (d->null && other.d->null) + return true; + if (d->x509 && other.d->x509) + return q_X509_cmp(d->x509, other.d->x509) == 0; + return false; +} + +bool QSslCertificate::isNull() const +{ + return d->null; +} + +bool QSslCertificate::isSelfSigned() const +{ + if (!d->x509) + return false; + + return (q_X509_check_issued(d->x509, d->x509) == X509_V_OK); +} + +QByteArray QSslCertificate::version() const +{ + QMutexLocker lock(QMutexPool::globalInstanceGet(d.data())); + if (d->versionString.isEmpty() && d->x509) + d->versionString = + QByteArray::number(qlonglong(q_ASN1_INTEGER_get(d->x509->cert_info->version)) + 1); + + return d->versionString; +} + +QByteArray QSslCertificate::serialNumber() const +{ + QMutexLocker lock(QMutexPool::globalInstanceGet(d.data())); + if (d->serialNumberString.isEmpty() && d->x509) { + ASN1_INTEGER *serialNumber = d->x509->cert_info->serialNumber; + QByteArray hexString; + hexString.reserve(serialNumber->length * 3); + for (int a = 0; a < serialNumber->length; ++a) { + hexString += QByteArray::number(serialNumber->data[a], 16).rightJustified(2, '0'); + hexString += ':'; + } + hexString.chop(1); + d->serialNumberString = hexString; + } + return d->serialNumberString; +} + +QStringList QSslCertificate::issuerInfo(SubjectInfo info) const +{ + QMutexLocker lock(QMutexPool::globalInstanceGet(d.data())); + // lazy init + if (d->issuerInfo.isEmpty() && d->x509) + d->issuerInfo = + _q_mapFromX509Name(q_X509_get_issuer_name(d->x509)); + + return d->issuerInfo.values(d->subjectInfoToString(info)); +} + +QStringList QSslCertificate::issuerInfo(const QByteArray &attribute) const +{ + QMutexLocker lock(QMutexPool::globalInstanceGet(d.data())); + // lazy init + if (d->issuerInfo.isEmpty() && d->x509) + d->issuerInfo = + _q_mapFromX509Name(q_X509_get_issuer_name(d->x509)); + + return d->issuerInfo.values(attribute); +} + +QStringList QSslCertificate::subjectInfo(SubjectInfo info) const +{ + QMutexLocker lock(QMutexPool::globalInstanceGet(d.data())); + // lazy init + if (d->subjectInfo.isEmpty() && d->x509) + d->subjectInfo = + _q_mapFromX509Name(q_X509_get_subject_name(d->x509)); + + return d->subjectInfo.values(d->subjectInfoToString(info)); +} + +QStringList QSslCertificate::subjectInfo(const QByteArray &attribute) const +{ + QMutexLocker lock(QMutexPool::globalInstanceGet(d.data())); + // lazy init + if (d->subjectInfo.isEmpty() && d->x509) + d->subjectInfo = + _q_mapFromX509Name(q_X509_get_subject_name(d->x509)); + + return d->subjectInfo.values(attribute); +} + +QList QSslCertificate::subjectInfoAttributes() const +{ + QMutexLocker lock(QMutexPool::globalInstanceGet(d.data())); + // lazy init + if (d->subjectInfo.isEmpty() && d->x509) + d->subjectInfo = + _q_mapFromX509Name(q_X509_get_subject_name(d->x509)); + + return d->subjectInfo.uniqueKeys(); +} + +QList QSslCertificate::issuerInfoAttributes() const +{ + QMutexLocker lock(QMutexPool::globalInstanceGet(d.data())); + // lazy init + if (d->issuerInfo.isEmpty() && d->x509) + d->issuerInfo = + _q_mapFromX509Name(q_X509_get_issuer_name(d->x509)); + + return d->issuerInfo.uniqueKeys(); +} + +QMultiMap QSslCertificate::subjectAlternativeNames() const +{ + QMultiMap result; + + if (!d->x509) + return result; + + STACK_OF(GENERAL_NAME) *altNames = (STACK_OF(GENERAL_NAME)*)q_X509_get_ext_d2i(d->x509, NID_subject_alt_name, 0, 0); + + if (altNames) { + for (int i = 0; i < q_sk_GENERAL_NAME_num(altNames); ++i) { + const GENERAL_NAME *genName = q_sk_GENERAL_NAME_value(altNames, i); + if (genName->type != GEN_DNS && genName->type != GEN_EMAIL) + continue; + + int len = q_ASN1_STRING_length(genName->d.ia5); + if (len < 0 || len >= 8192) { + // broken name + continue; + } + + const char *altNameStr = reinterpret_cast(q_ASN1_STRING_data(genName->d.ia5)); + const QString altName = QString::fromLatin1(altNameStr, len); + if (genName->type == GEN_DNS) + result.insert(QSsl::DnsEntry, altName); + else if (genName->type == GEN_EMAIL) + result.insert(QSsl::EmailEntry, altName); + } + q_sk_pop_free((STACK*)altNames, reinterpret_cast(q_sk_free)); + } + + return result; +} + +QDateTime QSslCertificate::effectiveDate() const +{ + return d->notValidBefore; +} + +QDateTime QSslCertificate::expiryDate() const +{ + return d->notValidAfter; +} + +Qt::HANDLE QSslCertificate::handle() const +{ + return Qt::HANDLE(d->x509); +} + +QSslKey QSslCertificate::publicKey() const +{ + if (!d->x509) + return QSslKey(); + + QSslKey key; + + key.d->type = QSsl::PublicKey; + X509_PUBKEY *xkey = d->x509->cert_info->key; + EVP_PKEY *pkey = q_X509_PUBKEY_get(xkey); + Q_ASSERT(pkey); + + if (q_EVP_PKEY_type(pkey->type) == EVP_PKEY_RSA) { + key.d->rsa = q_EVP_PKEY_get1_RSA(pkey); + key.d->algorithm = QSsl::Rsa; + key.d->isNull = false; + } else if (q_EVP_PKEY_type(pkey->type) == EVP_PKEY_DSA) { + key.d->dsa = q_EVP_PKEY_get1_DSA(pkey); + key.d->algorithm = QSsl::Dsa; + key.d->isNull = false; + } else if (q_EVP_PKEY_type(pkey->type) == EVP_PKEY_DH) { + // DH unsupported + } else { + // error? + } + + q_EVP_PKEY_free(pkey); + return key; +} + +/* + * Convert unknown extensions to a QVariant. + */ +static QVariant x509UnknownExtensionToValue(X509_EXTENSION *ext) +{ + // Get the extension specific method object if available + // we cast away the const-ness here because some versions of openssl + // don't use const for the parameters in the functions pointers stored + // in the object. + X509V3_EXT_METHOD *meth = const_cast(q_X509V3_EXT_get(ext)); + if (!meth) { + ASN1_OCTET_STRING *value = q_X509_EXTENSION_get_data(ext); + QByteArray result( reinterpret_cast(q_ASN1_STRING_data(value)), + q_ASN1_STRING_length(value)); + return result; + } + + //const unsigned char *data = ext->value->data; + void *ext_internal = q_X509V3_EXT_d2i(ext); + + // If this extension can be converted + if (meth->i2v && ext_internal) { + STACK_OF(CONF_VALUE) *val = meth->i2v(meth, ext_internal, 0); + + QVariantMap map; + QVariantList list; + bool isMap = false; + + for (int j = 0; j < q_SKM_sk_num(CONF_VALUE, val); j++) { + CONF_VALUE *nval = q_SKM_sk_value(CONF_VALUE, val, j); + if (nval->name && nval->value) { + isMap = true; + map[QString::fromUtf8(nval->name)] = QString::fromUtf8(nval->value); + } else if (nval->name) { + list << QString::fromUtf8(nval->name); + } else if (nval->value) { + list << QString::fromUtf8(nval->value); + } + } + + if (isMap) + return map; + else + return list; + } else if (meth->i2s && ext_internal) { + //qDebug() << meth->i2s(meth, ext_internal); + QVariant result(QString::fromUtf8(meth->i2s(meth, ext_internal))); + return result; + } else if (meth->i2r && ext_internal) { + QByteArray result; + + BIO *bio = q_BIO_new(q_BIO_s_mem()); + if (!bio) + return result; + + meth->i2r(meth, ext_internal, bio, 0); + + char *bio_buffer; + long bio_size = q_BIO_get_mem_data(bio, &bio_buffer); + result = QByteArray(bio_buffer, bio_size); + + q_BIO_free(bio); + return result; + } + + return QVariant(); +} + +/* + * Convert extensions to a variant. The naming of the keys of the map are + * taken from RFC 5280, however we decided the capitalisation in the RFC + * was too silly for the real world. + */ +static QVariant x509ExtensionToValue(X509_EXTENSION *ext) +{ + ASN1_OBJECT *obj = q_X509_EXTENSION_get_object(ext); + int nid = q_OBJ_obj2nid(obj); + + switch (nid) { + case NID_basic_constraints: + { + BASIC_CONSTRAINTS *basic = reinterpret_cast(q_X509V3_EXT_d2i(ext)); + + QVariantMap result; + result[QLatin1String("ca")] = basic->ca ? true : false; + if (basic->pathlen) + result[QLatin1String("pathLenConstraint")] = (qlonglong)q_ASN1_INTEGER_get(basic->pathlen); + + q_BASIC_CONSTRAINTS_free(basic); + return result; + } + break; + case NID_info_access: + { + AUTHORITY_INFO_ACCESS *info = reinterpret_cast(q_X509V3_EXT_d2i(ext)); + + QVariantMap result; + for (int i=0; i < q_SKM_sk_num(ACCESS_DESCRIPTION, info); i++) { + ACCESS_DESCRIPTION *ad = q_SKM_sk_value(ACCESS_DESCRIPTION, info, i); + + GENERAL_NAME *name = ad->location; + if (name->type == GEN_URI) { + int len = q_ASN1_STRING_length(name->d.uniformResourceIdentifier); + if (len < 0 || len >= 8192) { + // broken name + continue; + } + + const char *uriStr = reinterpret_cast(q_ASN1_STRING_data(name->d.uniformResourceIdentifier)); + const QString uri = QString::fromUtf8(uriStr, len); + + result[QString::fromUtf8(QSslCertificatePrivate::asn1ObjectName(ad->method))] = uri; + } else { + qWarning() << "Strange location type" << name->type; + } + } + +#if OPENSSL_VERSION_NUMBER >= 0x10000000L + q_sk_pop_free((_STACK*)info, reinterpret_cast(q_sk_free)); +#else + q_sk_pop_free((STACK*)info, reinterpret_cast(q_sk_free)); +#endif + return result; + } + break; + case NID_subject_key_identifier: + { + void *ext_internal = q_X509V3_EXT_d2i(ext); + + // we cast away the const-ness here because some versions of openssl + // don't use const for the parameters in the functions pointers stored + // in the object. + X509V3_EXT_METHOD *meth = const_cast(q_X509V3_EXT_get(ext)); + + return QVariant(QString::fromUtf8(meth->i2s(meth, ext_internal))); + } + break; + case NID_authority_key_identifier: + { + AUTHORITY_KEYID *auth_key = reinterpret_cast(q_X509V3_EXT_d2i(ext)); + + QVariantMap result; + + // keyid + if (auth_key->keyid) { + QByteArray keyid(reinterpret_cast(auth_key->keyid->data), + auth_key->keyid->length); + result[QLatin1String("keyid")] = keyid.toHex(); + } + + // issuer + // TODO: GENERAL_NAMES + + // serial + if (auth_key->serial) + result[QLatin1String("serial")] = (qlonglong)q_ASN1_INTEGER_get(auth_key->serial); + + q_AUTHORITY_KEYID_free(auth_key); + return result; + } + break; + } + + return QVariant(); +} + +QSslCertificateExtension QSslCertificatePrivate::convertExtension(X509_EXTENSION *ext) +{ + QSslCertificateExtension result; + + ASN1_OBJECT *obj = q_X509_EXTENSION_get_object(ext); + QByteArray oid = QSslCertificatePrivate::asn1ObjectId(obj); + QByteArray name = QSslCertificatePrivate::asn1ObjectName(obj); + + result.d->oid = QString::fromUtf8(oid); + result.d->name = QString::fromUtf8(name); + + bool critical = q_X509_EXTENSION_get_critical(ext); + result.d->critical = critical; + + // Lets see if we have custom support for this one + QVariant extensionValue = x509ExtensionToValue(ext); + if (extensionValue.isValid()) { + result.d->value = extensionValue; + result.d->supported = true; + + return result; + } + + extensionValue = x509UnknownExtensionToValue(ext); + if (extensionValue.isValid()) { + result.d->value = extensionValue; + result.d->supported = false; + return result; + } + + return result; +} + +QList QSslCertificate::extensions() const +{ + QList result; + + if (!d->x509) + return result; + + int count = q_X509_get_ext_count(d->x509); + + for (int i=0; i < count; i++) { + X509_EXTENSION *ext = q_X509_get_ext(d->x509, i); + result << QSslCertificatePrivate::convertExtension(ext); + } + + return result; +} + +QByteArray QSslCertificate::toPem() const +{ + if (!d->x509) + return QByteArray(); + return d->QByteArray_from_X509(d->x509, QSsl::Pem); +} + +QByteArray QSslCertificate::toDer() const +{ + if (!d->x509) + return QByteArray(); + return d->QByteArray_from_X509(d->x509, QSsl::Der); +} + +QString QSslCertificate::toText() const +{ + if (!d->x509) + return QString(); + return d->text_from_X509(d->x509); +} + +#define BEGINCERTSTRING "-----BEGIN CERTIFICATE-----" +#define ENDCERTSTRING "-----END CERTIFICATE-----" + +void QSslCertificatePrivate::init(const QByteArray &data, QSsl::EncodingFormat format) +{ + if (!data.isEmpty()) { + QList certs = (format == QSsl::Pem) + ? certificatesFromPem(data, 1) + : certificatesFromDer(data, 1); + if (!certs.isEmpty()) { + *this = *certs.first().d; + if (x509) + x509 = q_X509_dup(x509); + } + } +} + +// ### refactor against QSsl::pemFromDer() etc. (to avoid redundant implementations) +QByteArray QSslCertificatePrivate::QByteArray_from_X509(X509 *x509, QSsl::EncodingFormat format) +{ + if (!x509) { + qWarning("QSslSocketBackendPrivate::X509_to_QByteArray: null X509"); + return QByteArray(); + } + + // Use i2d_X509 to convert the X509 to an array. + int length = q_i2d_X509(x509, 0); + QByteArray array; + array.resize(length); + char *data = array.data(); + char **dataP = &data; + unsigned char **dataPu = (unsigned char **)dataP; + if (q_i2d_X509(x509, dataPu) < 0) + return QByteArray(); + + if (format == QSsl::Der) + return array; + + // Convert to Base64 - wrap at 64 characters. + array = array.toBase64(); + QByteArray tmp; + for (int i = 0; i <= array.size() - 64; i += 64) { + tmp += QByteArray::fromRawData(array.data() + i, 64); + tmp += '\n'; + } + if (int remainder = array.size() % 64) { + tmp += QByteArray::fromRawData(array.data() + array.size() - remainder, remainder); + tmp += '\n'; + } + + return BEGINCERTSTRING "\n" + tmp + ENDCERTSTRING "\n"; +} + +QString QSslCertificatePrivate::text_from_X509(X509 *x509) +{ + if (!x509) { + qWarning("QSslSocketBackendPrivate::text_from_X509: null X509"); + return QString(); + } + + QByteArray result; + BIO *bio = q_BIO_new(q_BIO_s_mem()); + if (!bio) + return QString(); + + q_X509_print(bio, x509); + + QVarLengthArray data; + int count = q_BIO_read(bio, data.data(), 16384); + if ( count > 0 ) { + result = QByteArray( data.data(), count ); + } + + q_BIO_free(bio); + + return QString::fromLatin1(result); +} + +QByteArray QSslCertificatePrivate::asn1ObjectId(ASN1_OBJECT *object) +{ + char buf[80]; // The openssl docs a buffer length of 80 should be more than enough + q_OBJ_obj2txt(buf, sizeof(buf), object, 1); // the 1 says always use the oid not the long name + + return QByteArray(buf); +} + + +QByteArray QSslCertificatePrivate::asn1ObjectName(ASN1_OBJECT *object) +{ + int nid = q_OBJ_obj2nid(object); + if (nid != NID_undef) + return QByteArray(q_OBJ_nid2sn(nid)); + + return asn1ObjectId(object); +} + +static QMap _q_mapFromX509Name(X509_NAME *name) +{ + QMap info; + for (int i = 0; i < q_X509_NAME_entry_count(name); ++i) { + X509_NAME_ENTRY *e = q_X509_NAME_get_entry(name, i); + + QByteArray name = QSslCertificatePrivate::asn1ObjectName(q_X509_NAME_ENTRY_get_object(e)); + unsigned char *data = 0; + int size = q_ASN1_STRING_to_UTF8(&data, q_X509_NAME_ENTRY_get_data(e)); + info.insertMulti(name, QString::fromUtf8((char*)data, size)); + q_CRYPTO_free(data); + } + + return info; +} + +QSslCertificate QSslCertificatePrivate::QSslCertificate_from_X509(X509 *x509) +{ + QSslCertificate certificate; + if (!x509 || !QSslSocket::supportsSsl()) + return certificate; + + ASN1_TIME *nbef = q_X509_get_notBefore(x509); + ASN1_TIME *naft = q_X509_get_notAfter(x509); + certificate.d->notValidBefore = q_getTimeFromASN1(nbef); + certificate.d->notValidAfter = q_getTimeFromASN1(naft); + certificate.d->null = false; + certificate.d->x509 = q_X509_dup(x509); + + return certificate; +} + +static bool matchLineFeed(const QByteArray &pem, int *offset) +{ + char ch = 0; + + // ignore extra whitespace at the end of the line + while (*offset < pem.size() && (ch = pem.at(*offset)) == ' ') + ++*offset; + + if (ch == '\n') { + *offset += 1; + return true; + } + if (ch == '\r' && pem.size() > (*offset + 1) && pem.at(*offset + 1) == '\n') { + *offset += 2; + return true; + } + return false; +} + +QList QSslCertificatePrivate::certificatesFromPem(const QByteArray &pem, int count) +{ + QList certificates; + QSslSocketPrivate::ensureInitialized(); + + int offset = 0; + while (count == -1 || certificates.size() < count) { + int startPos = pem.indexOf(BEGINCERTSTRING, offset); + if (startPos == -1) + break; + startPos += sizeof(BEGINCERTSTRING) - 1; + if (!matchLineFeed(pem, &startPos)) + break; + + int endPos = pem.indexOf(ENDCERTSTRING, startPos); + if (endPos == -1) + break; + + offset = endPos + sizeof(ENDCERTSTRING) - 1; + if (offset < pem.size() && !matchLineFeed(pem, &offset)) + break; + + QByteArray decoded = QByteArray::fromBase64( + QByteArray::fromRawData(pem.data() + startPos, endPos - startPos)); +#if OPENSSL_VERSION_NUMBER >= 0x00908000L + const unsigned char *data = (const unsigned char *)decoded.data(); +#else + unsigned char *data = (unsigned char *)decoded.data(); +#endif + + if (X509 *x509 = q_d2i_X509(0, &data, decoded.size())) { + certificates << QSslCertificate_from_X509(x509); + q_X509_free(x509); + } + } + + return certificates; +} + +QList QSslCertificatePrivate::certificatesFromDer(const QByteArray &der, int count) +{ + QList certificates; + QSslSocketPrivate::ensureInitialized(); + + +#if OPENSSL_VERSION_NUMBER >= 0x00908000L + const unsigned char *data = (const unsigned char *)der.data(); +#else + unsigned char *data = (unsigned char *)der.data(); +#endif + int size = der.size(); + + while (count == -1 || certificates.size() < count) { + if (X509 *x509 = q_d2i_X509(0, &data, size)) { + certificates << QSslCertificate_from_X509(x509); + q_X509_free(x509); + } else { + break; + } + size -= ((char *)data - der.data()); + } + + return certificates; +} + +QT_END_NAMESPACE diff --git a/src/network/ssl/qsslcertificate_p.h b/src/network/ssl/qsslcertificate_p.h index 6cf6974543..4bee9edcb9 100644 --- a/src/network/ssl/qsslcertificate_p.h +++ b/src/network/ssl/qsslcertificate_p.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtNetwork module of the Qt Toolkit. @@ -40,8 +40,8 @@ ****************************************************************************/ -#ifndef QSSLCERTIFICATE_P_H -#define QSSLCERTIFICATE_P_H +#ifndef QSSLCERTIFICATE_OPENSSL_P_H +#define QSSLCERTIFICATE_OPENSSL_P_H #include "qsslcertificate.h" @@ -61,10 +61,18 @@ #include #include +#ifndef QT_NO_OPENSSL #include +#else +struct X509; +struct X509_EXTENSION; +struct ASN1_OBJECT; +#endif QT_BEGIN_NAMESPACE +// forward declaration + class QSslCertificatePrivate { public: @@ -76,8 +84,10 @@ public: ~QSslCertificatePrivate() { +#ifndef QT_NO_OPENSSL if (x509) q_X509_free(x509); +#endif } bool null; @@ -102,6 +112,7 @@ public: static QList certificatesFromDer(const QByteArray &der, int count = -1); static bool isBlacklisted(const QSslCertificate &certificate); static QSslCertificateExtension convertExtension(X509_EXTENSION *ext); + static QByteArray subjectInfoToString(QSslCertificate::SubjectInfo info); friend class QSslSocketBackendPrivate; @@ -110,4 +121,4 @@ public: QT_END_NAMESPACE -#endif +#endif // QSSLCERTIFICATE_OPENSSL_P_H diff --git a/src/network/ssl/qsslcontext.cpp b/src/network/ssl/qsslcontext.cpp deleted file mode 100644 index addf7a2ff5..0000000000 --- a/src/network/ssl/qsslcontext.cpp +++ /dev/null @@ -1,465 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Copyright (C) 2014 BlackBerry Limited. All rights reserved. -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtNetwork module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#include -#include - -#include "private/qsslcontext_p.h" -#include "private/qsslsocket_p.h" -#include "private/qsslsocket_openssl_p.h" -#include "private/qsslsocket_openssl_symbols_p.h" - -QT_BEGIN_NAMESPACE - -// defined in qsslsocket_openssl.cpp: -extern int q_X509Callback(int ok, X509_STORE_CTX *ctx); -extern QString getErrorsFromOpenSsl(); - -// Default DH params -// 1024-bit MODP Group with 160-bit Prime Order Subgroup -// From RFC 5114 -static unsigned const char dh1024_p[]={ - 0xB1,0x0B,0x8F,0x96,0xA0,0x80,0xE0,0x1D,0xDE,0x92,0xDE,0x5E, - 0xAE,0x5D,0x54,0xEC,0x52,0xC9,0x9F,0xBC,0xFB,0x06,0xA3,0xC6, - 0x9A,0x6A,0x9D,0xCA,0x52,0xD2,0x3B,0x61,0x60,0x73,0xE2,0x86, - 0x75,0xA2,0x3D,0x18,0x98,0x38,0xEF,0x1E,0x2E,0xE6,0x52,0xC0, - 0x13,0xEC,0xB4,0xAE,0xA9,0x06,0x11,0x23,0x24,0x97,0x5C,0x3C, - 0xD4,0x9B,0x83,0xBF,0xAC,0xCB,0xDD,0x7D,0x90,0xC4,0xBD,0x70, - 0x98,0x48,0x8E,0x9C,0x21,0x9A,0x73,0x72,0x4E,0xFF,0xD6,0xFA, - 0xE5,0x64,0x47,0x38,0xFA,0xA3,0x1A,0x4F,0xF5,0x5B,0xCC,0xC0, - 0xA1,0x51,0xAF,0x5F,0x0D,0xC8,0xB4,0xBD,0x45,0xBF,0x37,0xDF, - 0x36,0x5C,0x1A,0x65,0xE6,0x8C,0xFD,0xA7,0x6D,0x4D,0xA7,0x08, - 0xDF,0x1F,0xB2,0xBC,0x2E,0x4A,0x43,0x71 -}; - -static unsigned const char dh1024_g[]={ - 0xA4,0xD1,0xCB,0xD5,0xC3,0xFD,0x34,0x12,0x67,0x65,0xA4,0x42, - 0xEF,0xB9,0x99,0x05,0xF8,0x10,0x4D,0xD2,0x58,0xAC,0x50,0x7F, - 0xD6,0x40,0x6C,0xFF,0x14,0x26,0x6D,0x31,0x26,0x6F,0xEA,0x1E, - 0x5C,0x41,0x56,0x4B,0x77,0x7E,0x69,0x0F,0x55,0x04,0xF2,0x13, - 0x16,0x02,0x17,0xB4,0xB0,0x1B,0x88,0x6A,0x5E,0x91,0x54,0x7F, - 0x9E,0x27,0x49,0xF4,0xD7,0xFB,0xD7,0xD3,0xB9,0xA9,0x2E,0xE1, - 0x90,0x9D,0x0D,0x22,0x63,0xF8,0x0A,0x76,0xA6,0xA2,0x4C,0x08, - 0x7A,0x09,0x1F,0x53,0x1D,0xBF,0x0A,0x01,0x69,0xB6,0xA2,0x8A, - 0xD6,0x62,0xA4,0xD1,0x8E,0x73,0xAF,0xA3,0x2D,0x77,0x9D,0x59, - 0x18,0xD0,0x8B,0xC8,0x85,0x8F,0x4D,0xCE,0xF9,0x7C,0x2A,0x24, - 0x85,0x5E,0x6E,0xEB,0x22,0xB3,0xB2,0xE5 -}; - -static DH *get_dh1024() -{ - DH *dh = q_DH_new(); - if (!dh) - return 0; - - dh->p = q_BN_bin2bn(dh1024_p, sizeof(dh1024_p), 0); - dh->g = q_BN_bin2bn(dh1024_g, sizeof(dh1024_g), 0); - if (!dh->p || !dh->g) { - q_DH_free(dh); - return 0; - } - - return dh; -} - -QSslContext::QSslContext() - : ctx(0), - pkey(0), - session(0), - m_sessionTicketLifeTimeHint(-1) -{ -} - -QSslContext::~QSslContext() -{ - if (ctx) - // This will decrement the reference count by 1 and free the context eventually when possible - q_SSL_CTX_free(ctx); - - if (pkey) - q_EVP_PKEY_free(pkey); - - if (session) - q_SSL_SESSION_free(session); -} - -QSslContext* QSslContext::fromConfiguration(QSslSocket::SslMode mode, const QSslConfiguration &configuration, bool allowRootCertOnDemandLoading) -{ - QSslContext *sslContext = new QSslContext(); - sslContext->sslConfiguration = configuration; - sslContext->errorCode = QSslError::NoError; - - bool client = (mode == QSslSocket::SslClientMode); - - bool reinitialized = false; -init_context: - switch (sslContext->sslConfiguration.protocol()) { - case QSsl::SslV2: -#ifndef OPENSSL_NO_SSL2 - sslContext->ctx = q_SSL_CTX_new(client ? q_SSLv2_client_method() : q_SSLv2_server_method()); -#else - sslContext->ctx = 0; // SSL 2 not supported by the system, but chosen deliberately -> error -#endif - break; - case QSsl::SslV3: - sslContext->ctx = q_SSL_CTX_new(client ? q_SSLv3_client_method() : q_SSLv3_server_method()); - break; - case QSsl::SecureProtocols: // SslV2 will be disabled below - case QSsl::TlsV1SslV3: // SslV2 will be disabled below - case QSsl::AnyProtocol: - default: - sslContext->ctx = q_SSL_CTX_new(client ? q_SSLv23_client_method() : q_SSLv23_server_method()); - break; - case QSsl::TlsV1_0: - sslContext->ctx = q_SSL_CTX_new(client ? q_TLSv1_client_method() : q_TLSv1_server_method()); - break; - case QSsl::TlsV1_1: -#if OPENSSL_VERSION_NUMBER >= 0x10001000L - sslContext->ctx = q_SSL_CTX_new(client ? q_TLSv1_1_client_method() : q_TLSv1_1_server_method()); -#else - sslContext->ctx = 0; // TLS 1.1 not supported by the system, but chosen deliberately -> error -#endif - break; - case QSsl::TlsV1_2: -#if OPENSSL_VERSION_NUMBER >= 0x10001000L - sslContext->ctx = q_SSL_CTX_new(client ? q_TLSv1_2_client_method() : q_TLSv1_2_server_method()); -#else - sslContext->ctx = 0; // TLS 1.2 not supported by the system, but chosen deliberately -> error -#endif - break; - } - if (!sslContext->ctx) { - // After stopping Flash 10 the SSL library looses its ciphers. Try re-adding them - // by re-initializing the library. - if (!reinitialized) { - reinitialized = true; - if (q_SSL_library_init() == 1) - goto init_context; - } - - sslContext->errorStr = QSslSocket::tr("Error creating SSL context (%1)").arg(QSslSocketBackendPrivate::getErrorsFromOpenSsl()); - sslContext->errorCode = QSslError::UnspecifiedError; - return sslContext; - } - - // Enable bug workarounds. - long options = QSslSocketBackendPrivate::setupOpenSslOptions(configuration.protocol(), configuration.d->sslOptions); - q_SSL_CTX_set_options(sslContext->ctx, options); - -#if OPENSSL_VERSION_NUMBER >= 0x10000000L - // Tell OpenSSL to release memory early - // http://www.openssl.org/docs/ssl/SSL_CTX_set_mode.html - if (q_SSLeay() >= 0x10000000L) - q_SSL_CTX_set_mode(sslContext->ctx, SSL_MODE_RELEASE_BUFFERS); -#endif - - // Initialize ciphers - QByteArray cipherString; - int first = true; - QList ciphers = sslContext->sslConfiguration.ciphers(); - if (ciphers.isEmpty()) - ciphers = QSslSocketPrivate::defaultCiphers(); - foreach (const QSslCipher &cipher, ciphers) { - if (first) - first = false; - else - cipherString.append(':'); - cipherString.append(cipher.name().toLatin1()); - } - - if (!q_SSL_CTX_set_cipher_list(sslContext->ctx, cipherString.data())) { - sslContext->errorStr = QSslSocket::tr("Invalid or empty cipher list (%1)").arg(QSslSocketBackendPrivate::getErrorsFromOpenSsl()); - sslContext->errorCode = QSslError::UnspecifiedError; - return sslContext; - } - - // Add all our CAs to this store. - foreach (const QSslCertificate &caCertificate, sslContext->sslConfiguration.caCertificates()) { - // From https://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html: - // - // If several CA certificates matching the name, key identifier, and - // serial number condition are available, only the first one will be - // examined. This may lead to unexpected results if the same CA - // certificate is available with different expiration dates. If a - // ``certificate expired'' verification error occurs, no other - // certificate will be searched. Make sure to not have expired - // certificates mixed with valid ones. - // - // See also: QSslSocketBackendPrivate::verify() - if (caCertificate.expiryDate() >= QDateTime::currentDateTime()) { - q_X509_STORE_add_cert(sslContext->ctx->cert_store, (X509 *)caCertificate.handle()); - } - } - - if (QSslSocketPrivate::s_loadRootCertsOnDemand && allowRootCertOnDemandLoading) { - // tell OpenSSL the directories where to look up the root certs on demand - QList unixDirs = QSslSocketPrivate::unixRootCertDirectories(); - for (int a = 0; a < unixDirs.count(); ++a) - q_SSL_CTX_load_verify_locations(sslContext->ctx, 0, unixDirs.at(a).constData()); - } - - if (!sslContext->sslConfiguration.localCertificate().isNull()) { - // Require a private key as well. - if (sslContext->sslConfiguration.privateKey().isNull()) { - sslContext->errorStr = QSslSocket::tr("Cannot provide a certificate with no key, %1").arg(QSslSocketBackendPrivate::getErrorsFromOpenSsl()); - sslContext->errorCode = QSslError::UnspecifiedError; - return sslContext; - } - - // Load certificate - if (!q_SSL_CTX_use_certificate(sslContext->ctx, (X509 *)sslContext->sslConfiguration.localCertificate().handle())) { - sslContext->errorStr = QSslSocket::tr("Error loading local certificate, %1").arg(QSslSocketBackendPrivate::getErrorsFromOpenSsl()); - sslContext->errorCode = QSslError::UnspecifiedError; - return sslContext; - } - - if (configuration.d->privateKey.algorithm() == QSsl::Opaque) { - sslContext->pkey = reinterpret_cast(configuration.d->privateKey.handle()); - } else { - // Load private key - sslContext->pkey = q_EVP_PKEY_new(); - // before we were using EVP_PKEY_assign_R* functions and did not use EVP_PKEY_free. - // this lead to a memory leak. Now we use the *_set1_* functions which do not - // take ownership of the RSA/DSA key instance because the QSslKey already has ownership. - if (configuration.d->privateKey.algorithm() == QSsl::Rsa) - q_EVP_PKEY_set1_RSA(sslContext->pkey, reinterpret_cast(configuration.d->privateKey.handle())); - else - q_EVP_PKEY_set1_DSA(sslContext->pkey, reinterpret_cast(configuration.d->privateKey.handle())); - } - - if (!q_SSL_CTX_use_PrivateKey(sslContext->ctx, sslContext->pkey)) { - sslContext->errorStr = QSslSocket::tr("Error loading private key, %1").arg(QSslSocketBackendPrivate::getErrorsFromOpenSsl()); - sslContext->errorCode = QSslError::UnspecifiedError; - return sslContext; - } - if (configuration.d->privateKey.algorithm() == QSsl::Opaque) - sslContext->pkey = 0; // Don't free the private key, it belongs to QSslKey - - // Check if the certificate matches the private key. - if (!q_SSL_CTX_check_private_key(sslContext->ctx)) { - sslContext->errorStr = QSslSocket::tr("Private key does not certify public key, %1").arg(QSslSocketBackendPrivate::getErrorsFromOpenSsl()); - sslContext->errorCode = QSslError::UnspecifiedError; - return sslContext; - } - - // If we have any intermediate certificates then we need to add them to our chain - bool first = true; - foreach (const QSslCertificate &cert, configuration.d->localCertificateChain) { - if (first) { - first = false; - continue; - } - q_SSL_CTX_ctrl(sslContext->ctx, SSL_CTRL_EXTRA_CHAIN_CERT, 0, - q_X509_dup(reinterpret_cast(cert.handle()))); - } - } - - // Initialize peer verification. - if (sslContext->sslConfiguration.peerVerifyMode() == QSslSocket::VerifyNone) { - q_SSL_CTX_set_verify(sslContext->ctx, SSL_VERIFY_NONE, 0); - } else { - q_SSL_CTX_set_verify(sslContext->ctx, SSL_VERIFY_PEER, q_X509Callback); - } - - // Set verification depth. - if (sslContext->sslConfiguration.peerVerifyDepth() != 0) - q_SSL_CTX_set_verify_depth(sslContext->ctx, sslContext->sslConfiguration.peerVerifyDepth()); - - // set persisted session if the user set it - if (!configuration.sessionTicket().isEmpty()) - sslContext->setSessionASN1(configuration.sessionTicket()); - - // Set temp DH params - DH *dh = 0; - dh = get_dh1024(); - q_SSL_CTX_set_tmp_dh(sslContext->ctx, dh); - q_DH_free(dh); - -#ifndef OPENSSL_NO_EC - // Set temp ECDH params - EC_KEY *ecdh = 0; - ecdh = q_EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); - q_SSL_CTX_set_tmp_ecdh(sslContext->ctx, ecdh); - q_EC_KEY_free(ecdh); -#endif // OPENSSL_NO_EC - - return sslContext; -} - -#if OPENSSL_VERSION_NUMBER >= 0x1000100fL && !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) - -static int next_proto_cb(SSL *, unsigned char **out, unsigned char *outlen, - const unsigned char *in, unsigned int inlen, void *arg) -{ - QSslContext::NPNContext *ctx = reinterpret_cast(arg); - - // comment out to debug: -// QList supportedVersions; -// for (unsigned int i = 0; i < inlen; ) { -// QByteArray version(reinterpret_cast(&in[i+1]), in[i]); -// supportedVersions << version; -// i += in[i] + 1; -// } - - int proto = q_SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len); - switch (proto) { - case OPENSSL_NPN_UNSUPPORTED: - ctx->status = QSslConfiguration::NextProtocolNegotiationNone; - break; - case OPENSSL_NPN_NEGOTIATED: - ctx->status = QSslConfiguration::NextProtocolNegotiationNegotiated; - break; - case OPENSSL_NPN_NO_OVERLAP: - ctx->status = QSslConfiguration::NextProtocolNegotiationUnsupported; - break; - default: - qWarning("OpenSSL sent unknown NPN status"); - } - - return SSL_TLSEXT_ERR_OK; -} - -QSslContext::NPNContext QSslContext::npnContext() const -{ - return m_npnContext; -} -#endif // OPENSSL_VERSION_NUMBER >= 0x1000100fL ... - -// Needs to be deleted by caller -SSL* QSslContext::createSsl() -{ - SSL* ssl = q_SSL_new(ctx); - q_SSL_clear(ssl); - - if (!session && !sessionASN1().isEmpty() - && !sslConfiguration.testSslOption(QSsl::SslOptionDisableSessionPersistence)) { - const unsigned char *data = reinterpret_cast(m_sessionASN1.constData()); - session = q_d2i_SSL_SESSION(0, &data, m_sessionASN1.size()); // refcount is 1 already, set by function above - } - - if (session) { - // Try to resume the last session we cached - if (!q_SSL_set_session(ssl, session)) { - qWarning("could not set SSL session"); - q_SSL_SESSION_free(session); - session = 0; - } - } - -#if OPENSSL_VERSION_NUMBER >= 0x1000100fL && !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) - QList protocols = sslConfiguration.d->nextAllowedProtocols; - if (!protocols.isEmpty()) { - m_supportedNPNVersions.clear(); - for (int a = 0; a < protocols.count(); ++a) { - if (protocols.at(a).size() > 255) { - qWarning() << "TLS NPN extension" << protocols.at(a) - << "is too long and will be truncated to 255 characters."; - protocols[a] = protocols.at(a).left(255); - } - m_supportedNPNVersions.append(protocols.at(a).size()).append(protocols.at(a)); - } - m_npnContext.data = reinterpret_cast(m_supportedNPNVersions.data()); - m_npnContext.len = m_supportedNPNVersions.count(); - m_npnContext.status = QSslConfiguration::NextProtocolNegotiationNone; - q_SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &m_npnContext); - } -#endif // OPENSSL_VERSION_NUMBER >= 0x1000100fL ... - - return ssl; -} - -// We cache exactly one session here -bool QSslContext::cacheSession(SSL* ssl) -{ - // don't cache the same session again - if (session && session == q_SSL_get_session(ssl)) - return true; - - // decrease refcount of currently stored session - // (this might happen if there are several concurrent handshakes in flight) - if (session) - q_SSL_SESSION_free(session); - - // cache the session the caller gave us and increase reference count - session = q_SSL_get1_session(ssl); - - if (session && !sslConfiguration.testSslOption(QSsl::SslOptionDisableSessionPersistence)) { - int sessionSize = q_i2d_SSL_SESSION(session, 0); - if (sessionSize > 0) { - m_sessionASN1.resize(sessionSize); - unsigned char *data = reinterpret_cast(m_sessionASN1.data()); - if (!q_i2d_SSL_SESSION(session, &data)) - qWarning("could not store persistent version of SSL session"); - m_sessionTicketLifeTimeHint = session->tlsext_tick_lifetime_hint; - } - } - - return (session != 0); -} - -QByteArray QSslContext::sessionASN1() const -{ - return m_sessionASN1; -} - -void QSslContext::setSessionASN1(const QByteArray &session) -{ - m_sessionASN1 = session; -} - -int QSslContext::sessionTicketLifeTimeHint() const -{ - return m_sessionTicketLifeTimeHint; -} - -QSslError::SslError QSslContext::error() const -{ - return errorCode; -} - -QString QSslContext::errorString() const -{ - return errorStr; -} - -QT_END_NAMESPACE diff --git a/src/network/ssl/qsslcontext_openssl.cpp b/src/network/ssl/qsslcontext_openssl.cpp new file mode 100644 index 0000000000..0ca14f199e --- /dev/null +++ b/src/network/ssl/qsslcontext_openssl.cpp @@ -0,0 +1,465 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). +** Copyright (C) 2014 BlackBerry Limited. All rights reserved. +** Contact: http://www.qt-project.org/legal +** +** This file is part of the QtNetwork module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + + +#include +#include + +#include "private/qsslcontext_openssl_p.h" +#include "private/qsslsocket_p.h" +#include "private/qsslsocket_openssl_p.h" +#include "private/qsslsocket_openssl_symbols_p.h" + +QT_BEGIN_NAMESPACE + +// defined in qsslsocket_openssl.cpp: +extern int q_X509Callback(int ok, X509_STORE_CTX *ctx); +extern QString getErrorsFromOpenSsl(); + +// Default DH params +// 1024-bit MODP Group with 160-bit Prime Order Subgroup +// From RFC 5114 +static unsigned const char dh1024_p[]={ + 0xB1,0x0B,0x8F,0x96,0xA0,0x80,0xE0,0x1D,0xDE,0x92,0xDE,0x5E, + 0xAE,0x5D,0x54,0xEC,0x52,0xC9,0x9F,0xBC,0xFB,0x06,0xA3,0xC6, + 0x9A,0x6A,0x9D,0xCA,0x52,0xD2,0x3B,0x61,0x60,0x73,0xE2,0x86, + 0x75,0xA2,0x3D,0x18,0x98,0x38,0xEF,0x1E,0x2E,0xE6,0x52,0xC0, + 0x13,0xEC,0xB4,0xAE,0xA9,0x06,0x11,0x23,0x24,0x97,0x5C,0x3C, + 0xD4,0x9B,0x83,0xBF,0xAC,0xCB,0xDD,0x7D,0x90,0xC4,0xBD,0x70, + 0x98,0x48,0x8E,0x9C,0x21,0x9A,0x73,0x72,0x4E,0xFF,0xD6,0xFA, + 0xE5,0x64,0x47,0x38,0xFA,0xA3,0x1A,0x4F,0xF5,0x5B,0xCC,0xC0, + 0xA1,0x51,0xAF,0x5F,0x0D,0xC8,0xB4,0xBD,0x45,0xBF,0x37,0xDF, + 0x36,0x5C,0x1A,0x65,0xE6,0x8C,0xFD,0xA7,0x6D,0x4D,0xA7,0x08, + 0xDF,0x1F,0xB2,0xBC,0x2E,0x4A,0x43,0x71 +}; + +static unsigned const char dh1024_g[]={ + 0xA4,0xD1,0xCB,0xD5,0xC3,0xFD,0x34,0x12,0x67,0x65,0xA4,0x42, + 0xEF,0xB9,0x99,0x05,0xF8,0x10,0x4D,0xD2,0x58,0xAC,0x50,0x7F, + 0xD6,0x40,0x6C,0xFF,0x14,0x26,0x6D,0x31,0x26,0x6F,0xEA,0x1E, + 0x5C,0x41,0x56,0x4B,0x77,0x7E,0x69,0x0F,0x55,0x04,0xF2,0x13, + 0x16,0x02,0x17,0xB4,0xB0,0x1B,0x88,0x6A,0x5E,0x91,0x54,0x7F, + 0x9E,0x27,0x49,0xF4,0xD7,0xFB,0xD7,0xD3,0xB9,0xA9,0x2E,0xE1, + 0x90,0x9D,0x0D,0x22,0x63,0xF8,0x0A,0x76,0xA6,0xA2,0x4C,0x08, + 0x7A,0x09,0x1F,0x53,0x1D,0xBF,0x0A,0x01,0x69,0xB6,0xA2,0x8A, + 0xD6,0x62,0xA4,0xD1,0x8E,0x73,0xAF,0xA3,0x2D,0x77,0x9D,0x59, + 0x18,0xD0,0x8B,0xC8,0x85,0x8F,0x4D,0xCE,0xF9,0x7C,0x2A,0x24, + 0x85,0x5E,0x6E,0xEB,0x22,0xB3,0xB2,0xE5 +}; + +static DH *get_dh1024() +{ + DH *dh = q_DH_new(); + if (!dh) + return 0; + + dh->p = q_BN_bin2bn(dh1024_p, sizeof(dh1024_p), 0); + dh->g = q_BN_bin2bn(dh1024_g, sizeof(dh1024_g), 0); + if (!dh->p || !dh->g) { + q_DH_free(dh); + return 0; + } + + return dh; +} + +QSslContext::QSslContext() + : ctx(0), + pkey(0), + session(0), + m_sessionTicketLifeTimeHint(-1) +{ +} + +QSslContext::~QSslContext() +{ + if (ctx) + // This will decrement the reference count by 1 and free the context eventually when possible + q_SSL_CTX_free(ctx); + + if (pkey) + q_EVP_PKEY_free(pkey); + + if (session) + q_SSL_SESSION_free(session); +} + +QSslContext* QSslContext::fromConfiguration(QSslSocket::SslMode mode, const QSslConfiguration &configuration, bool allowRootCertOnDemandLoading) +{ + QSslContext *sslContext = new QSslContext(); + sslContext->sslConfiguration = configuration; + sslContext->errorCode = QSslError::NoError; + + bool client = (mode == QSslSocket::SslClientMode); + + bool reinitialized = false; +init_context: + switch (sslContext->sslConfiguration.protocol()) { + case QSsl::SslV2: +#ifndef OPENSSL_NO_SSL2 + sslContext->ctx = q_SSL_CTX_new(client ? q_SSLv2_client_method() : q_SSLv2_server_method()); +#else + sslContext->ctx = 0; // SSL 2 not supported by the system, but chosen deliberately -> error +#endif + break; + case QSsl::SslV3: + sslContext->ctx = q_SSL_CTX_new(client ? q_SSLv3_client_method() : q_SSLv3_server_method()); + break; + case QSsl::SecureProtocols: // SslV2 will be disabled below + case QSsl::TlsV1SslV3: // SslV2 will be disabled below + case QSsl::AnyProtocol: + default: + sslContext->ctx = q_SSL_CTX_new(client ? q_SSLv23_client_method() : q_SSLv23_server_method()); + break; + case QSsl::TlsV1_0: + sslContext->ctx = q_SSL_CTX_new(client ? q_TLSv1_client_method() : q_TLSv1_server_method()); + break; + case QSsl::TlsV1_1: +#if OPENSSL_VERSION_NUMBER >= 0x10001000L + sslContext->ctx = q_SSL_CTX_new(client ? q_TLSv1_1_client_method() : q_TLSv1_1_server_method()); +#else + sslContext->ctx = 0; // TLS 1.1 not supported by the system, but chosen deliberately -> error +#endif + break; + case QSsl::TlsV1_2: +#if OPENSSL_VERSION_NUMBER >= 0x10001000L + sslContext->ctx = q_SSL_CTX_new(client ? q_TLSv1_2_client_method() : q_TLSv1_2_server_method()); +#else + sslContext->ctx = 0; // TLS 1.2 not supported by the system, but chosen deliberately -> error +#endif + break; + } + if (!sslContext->ctx) { + // After stopping Flash 10 the SSL library looses its ciphers. Try re-adding them + // by re-initializing the library. + if (!reinitialized) { + reinitialized = true; + if (q_SSL_library_init() == 1) + goto init_context; + } + + sslContext->errorStr = QSslSocket::tr("Error creating SSL context (%1)").arg(QSslSocketBackendPrivate::getErrorsFromOpenSsl()); + sslContext->errorCode = QSslError::UnspecifiedError; + return sslContext; + } + + // Enable bug workarounds. + long options = QSslSocketBackendPrivate::setupOpenSslOptions(configuration.protocol(), configuration.d->sslOptions); + q_SSL_CTX_set_options(sslContext->ctx, options); + +#if OPENSSL_VERSION_NUMBER >= 0x10000000L + // Tell OpenSSL to release memory early + // http://www.openssl.org/docs/ssl/SSL_CTX_set_mode.html + if (q_SSLeay() >= 0x10000000L) + q_SSL_CTX_set_mode(sslContext->ctx, SSL_MODE_RELEASE_BUFFERS); +#endif + + // Initialize ciphers + QByteArray cipherString; + int first = true; + QList ciphers = sslContext->sslConfiguration.ciphers(); + if (ciphers.isEmpty()) + ciphers = QSslSocketPrivate::defaultCiphers(); + foreach (const QSslCipher &cipher, ciphers) { + if (first) + first = false; + else + cipherString.append(':'); + cipherString.append(cipher.name().toLatin1()); + } + + if (!q_SSL_CTX_set_cipher_list(sslContext->ctx, cipherString.data())) { + sslContext->errorStr = QSslSocket::tr("Invalid or empty cipher list (%1)").arg(QSslSocketBackendPrivate::getErrorsFromOpenSsl()); + sslContext->errorCode = QSslError::UnspecifiedError; + return sslContext; + } + + // Add all our CAs to this store. + foreach (const QSslCertificate &caCertificate, sslContext->sslConfiguration.caCertificates()) { + // From https://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html: + // + // If several CA certificates matching the name, key identifier, and + // serial number condition are available, only the first one will be + // examined. This may lead to unexpected results if the same CA + // certificate is available with different expiration dates. If a + // ``certificate expired'' verification error occurs, no other + // certificate will be searched. Make sure to not have expired + // certificates mixed with valid ones. + // + // See also: QSslSocketBackendPrivate::verify() + if (caCertificate.expiryDate() >= QDateTime::currentDateTime()) { + q_X509_STORE_add_cert(sslContext->ctx->cert_store, (X509 *)caCertificate.handle()); + } + } + + if (QSslSocketPrivate::s_loadRootCertsOnDemand && allowRootCertOnDemandLoading) { + // tell OpenSSL the directories where to look up the root certs on demand + QList unixDirs = QSslSocketPrivate::unixRootCertDirectories(); + for (int a = 0; a < unixDirs.count(); ++a) + q_SSL_CTX_load_verify_locations(sslContext->ctx, 0, unixDirs.at(a).constData()); + } + + if (!sslContext->sslConfiguration.localCertificate().isNull()) { + // Require a private key as well. + if (sslContext->sslConfiguration.privateKey().isNull()) { + sslContext->errorStr = QSslSocket::tr("Cannot provide a certificate with no key, %1").arg(QSslSocketBackendPrivate::getErrorsFromOpenSsl()); + sslContext->errorCode = QSslError::UnspecifiedError; + return sslContext; + } + + // Load certificate + if (!q_SSL_CTX_use_certificate(sslContext->ctx, (X509 *)sslContext->sslConfiguration.localCertificate().handle())) { + sslContext->errorStr = QSslSocket::tr("Error loading local certificate, %1").arg(QSslSocketBackendPrivate::getErrorsFromOpenSsl()); + sslContext->errorCode = QSslError::UnspecifiedError; + return sslContext; + } + + if (configuration.d->privateKey.algorithm() == QSsl::Opaque) { + sslContext->pkey = reinterpret_cast(configuration.d->privateKey.handle()); + } else { + // Load private key + sslContext->pkey = q_EVP_PKEY_new(); + // before we were using EVP_PKEY_assign_R* functions and did not use EVP_PKEY_free. + // this lead to a memory leak. Now we use the *_set1_* functions which do not + // take ownership of the RSA/DSA key instance because the QSslKey already has ownership. + if (configuration.d->privateKey.algorithm() == QSsl::Rsa) + q_EVP_PKEY_set1_RSA(sslContext->pkey, reinterpret_cast(configuration.d->privateKey.handle())); + else + q_EVP_PKEY_set1_DSA(sslContext->pkey, reinterpret_cast(configuration.d->privateKey.handle())); + } + + if (!q_SSL_CTX_use_PrivateKey(sslContext->ctx, sslContext->pkey)) { + sslContext->errorStr = QSslSocket::tr("Error loading private key, %1").arg(QSslSocketBackendPrivate::getErrorsFromOpenSsl()); + sslContext->errorCode = QSslError::UnspecifiedError; + return sslContext; + } + if (configuration.d->privateKey.algorithm() == QSsl::Opaque) + sslContext->pkey = 0; // Don't free the private key, it belongs to QSslKey + + // Check if the certificate matches the private key. + if (!q_SSL_CTX_check_private_key(sslContext->ctx)) { + sslContext->errorStr = QSslSocket::tr("Private key does not certify public key, %1").arg(QSslSocketBackendPrivate::getErrorsFromOpenSsl()); + sslContext->errorCode = QSslError::UnspecifiedError; + return sslContext; + } + + // If we have any intermediate certificates then we need to add them to our chain + bool first = true; + foreach (const QSslCertificate &cert, configuration.d->localCertificateChain) { + if (first) { + first = false; + continue; + } + q_SSL_CTX_ctrl(sslContext->ctx, SSL_CTRL_EXTRA_CHAIN_CERT, 0, + q_X509_dup(reinterpret_cast(cert.handle()))); + } + } + + // Initialize peer verification. + if (sslContext->sslConfiguration.peerVerifyMode() == QSslSocket::VerifyNone) { + q_SSL_CTX_set_verify(sslContext->ctx, SSL_VERIFY_NONE, 0); + } else { + q_SSL_CTX_set_verify(sslContext->ctx, SSL_VERIFY_PEER, q_X509Callback); + } + + // Set verification depth. + if (sslContext->sslConfiguration.peerVerifyDepth() != 0) + q_SSL_CTX_set_verify_depth(sslContext->ctx, sslContext->sslConfiguration.peerVerifyDepth()); + + // set persisted session if the user set it + if (!configuration.sessionTicket().isEmpty()) + sslContext->setSessionASN1(configuration.sessionTicket()); + + // Set temp DH params + DH *dh = 0; + dh = get_dh1024(); + q_SSL_CTX_set_tmp_dh(sslContext->ctx, dh); + q_DH_free(dh); + +#ifndef OPENSSL_NO_EC + // Set temp ECDH params + EC_KEY *ecdh = 0; + ecdh = q_EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); + q_SSL_CTX_set_tmp_ecdh(sslContext->ctx, ecdh); + q_EC_KEY_free(ecdh); +#endif // OPENSSL_NO_EC + + return sslContext; +} + +#if OPENSSL_VERSION_NUMBER >= 0x1000100fL && !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) + +static int next_proto_cb(SSL *, unsigned char **out, unsigned char *outlen, + const unsigned char *in, unsigned int inlen, void *arg) +{ + QSslContext::NPNContext *ctx = reinterpret_cast(arg); + + // comment out to debug: +// QList supportedVersions; +// for (unsigned int i = 0; i < inlen; ) { +// QByteArray version(reinterpret_cast(&in[i+1]), in[i]); +// supportedVersions << version; +// i += in[i] + 1; +// } + + int proto = q_SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len); + switch (proto) { + case OPENSSL_NPN_UNSUPPORTED: + ctx->status = QSslConfiguration::NextProtocolNegotiationNone; + break; + case OPENSSL_NPN_NEGOTIATED: + ctx->status = QSslConfiguration::NextProtocolNegotiationNegotiated; + break; + case OPENSSL_NPN_NO_OVERLAP: + ctx->status = QSslConfiguration::NextProtocolNegotiationUnsupported; + break; + default: + qWarning("OpenSSL sent unknown NPN status"); + } + + return SSL_TLSEXT_ERR_OK; +} + +QSslContext::NPNContext QSslContext::npnContext() const +{ + return m_npnContext; +} +#endif // OPENSSL_VERSION_NUMBER >= 0x1000100fL ... + +// Needs to be deleted by caller +SSL* QSslContext::createSsl() +{ + SSL* ssl = q_SSL_new(ctx); + q_SSL_clear(ssl); + + if (!session && !sessionASN1().isEmpty() + && !sslConfiguration.testSslOption(QSsl::SslOptionDisableSessionPersistence)) { + const unsigned char *data = reinterpret_cast(m_sessionASN1.constData()); + session = q_d2i_SSL_SESSION(0, &data, m_sessionASN1.size()); // refcount is 1 already, set by function above + } + + if (session) { + // Try to resume the last session we cached + if (!q_SSL_set_session(ssl, session)) { + qWarning("could not set SSL session"); + q_SSL_SESSION_free(session); + session = 0; + } + } + +#if OPENSSL_VERSION_NUMBER >= 0x1000100fL && !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) + QList protocols = sslConfiguration.d->nextAllowedProtocols; + if (!protocols.isEmpty()) { + m_supportedNPNVersions.clear(); + for (int a = 0; a < protocols.count(); ++a) { + if (protocols.at(a).size() > 255) { + qWarning() << "TLS NPN extension" << protocols.at(a) + << "is too long and will be truncated to 255 characters."; + protocols[a] = protocols.at(a).left(255); + } + m_supportedNPNVersions.append(protocols.at(a).size()).append(protocols.at(a)); + } + m_npnContext.data = reinterpret_cast(m_supportedNPNVersions.data()); + m_npnContext.len = m_supportedNPNVersions.count(); + m_npnContext.status = QSslConfiguration::NextProtocolNegotiationNone; + q_SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &m_npnContext); + } +#endif // OPENSSL_VERSION_NUMBER >= 0x1000100fL ... + + return ssl; +} + +// We cache exactly one session here +bool QSslContext::cacheSession(SSL* ssl) +{ + // don't cache the same session again + if (session && session == q_SSL_get_session(ssl)) + return true; + + // decrease refcount of currently stored session + // (this might happen if there are several concurrent handshakes in flight) + if (session) + q_SSL_SESSION_free(session); + + // cache the session the caller gave us and increase reference count + session = q_SSL_get1_session(ssl); + + if (session && !sslConfiguration.testSslOption(QSsl::SslOptionDisableSessionPersistence)) { + int sessionSize = q_i2d_SSL_SESSION(session, 0); + if (sessionSize > 0) { + m_sessionASN1.resize(sessionSize); + unsigned char *data = reinterpret_cast(m_sessionASN1.data()); + if (!q_i2d_SSL_SESSION(session, &data)) + qWarning("could not store persistent version of SSL session"); + m_sessionTicketLifeTimeHint = session->tlsext_tick_lifetime_hint; + } + } + + return (session != 0); +} + +QByteArray QSslContext::sessionASN1() const +{ + return m_sessionASN1; +} + +void QSslContext::setSessionASN1(const QByteArray &session) +{ + m_sessionASN1 = session; +} + +int QSslContext::sessionTicketLifeTimeHint() const +{ + return m_sessionTicketLifeTimeHint; +} + +QSslError::SslError QSslContext::error() const +{ + return errorCode; +} + +QString QSslContext::errorString() const +{ + return errorStr; +} + +QT_END_NAMESPACE diff --git a/src/network/ssl/qsslcontext_openssl_p.h b/src/network/ssl/qsslcontext_openssl_p.h new file mode 100644 index 0000000000..9fb9bd2204 --- /dev/null +++ b/src/network/ssl/qsslcontext_openssl_p.h @@ -0,0 +1,113 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). +** Copyright (C) 2014 BlackBerry Limited. All rights reserved. +** Contact: http://www.qt-project.org/legal +** +** This file is part of the QtNetwork module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + + +#ifndef QSSLCONTEXT_OPENSSL_P_H +#define QSSLCONTEXT_OPENSSL_P_H + +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +#ifndef QT_NO_SSL + +class QSslContextPrivate; + +class QSslContext +{ +public: + + ~QSslContext(); + + static QSslContext* fromConfiguration(QSslSocket::SslMode mode, const QSslConfiguration &configuration, + bool allowRootCertOnDemandLoading); + + QSslError::SslError error() const; + QString errorString() const; + + SSL* createSsl(); + bool cacheSession(SSL*); // should be called when handshake completed + + QByteArray sessionASN1() const; + void setSessionASN1(const QByteArray &sessionASN1); + int sessionTicketLifeTimeHint() const; + +#if OPENSSL_VERSION_NUMBER >= 0x1000100fL && !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) + // must be public because we want to use it from an OpenSSL callback + struct NPNContext { + NPNContext() : data(0), + len(0), + status(QSslConfiguration::NextProtocolNegotiationNone) + { } + unsigned char *data; + unsigned short len; + QSslConfiguration::NextProtocolNegotiationStatus status; + }; + NPNContext npnContext() const; +#endif // OPENSSL_VERSION_NUMBER >= 0x1000100fL ... + +protected: + QSslContext(); + +private: + SSL_CTX* ctx; + EVP_PKEY *pkey; + SSL_SESSION *session; + QByteArray m_sessionASN1; + int m_sessionTicketLifeTimeHint; + QSslError::SslError errorCode; + QString errorStr; + QSslConfiguration sslConfiguration; +#if OPENSSL_VERSION_NUMBER >= 0x1000100fL && !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) + QByteArray m_supportedNPNVersions; + NPNContext m_npnContext; +#endif // OPENSSL_VERSION_NUMBER >= 0x1000100fL ... +}; + +#endif // QT_NO_SSL + +QT_END_NAMESPACE + +#endif // QSSLCONTEXT_OPENSSL_P_H diff --git a/src/network/ssl/qsslcontext_p.h b/src/network/ssl/qsslcontext_p.h deleted file mode 100644 index 20b27c1ce7..0000000000 --- a/src/network/ssl/qsslcontext_p.h +++ /dev/null @@ -1,113 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Copyright (C) 2014 BlackBerry Limited. All rights reserved. -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtNetwork module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#ifndef QSSLCONTEXT_H -#define QSSLCONTEXT_H - -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -#ifndef QT_NO_SSL - -class QSslContextPrivate; - -class QSslContext -{ -public: - - ~QSslContext(); - - static QSslContext* fromConfiguration(QSslSocket::SslMode mode, const QSslConfiguration &configuration, - bool allowRootCertOnDemandLoading); - - QSslError::SslError error() const; - QString errorString() const; - - SSL* createSsl(); - bool cacheSession(SSL*); // should be called when handshake completed - - QByteArray sessionASN1() const; - void setSessionASN1(const QByteArray &sessionASN1); - int sessionTicketLifeTimeHint() const; - -#if OPENSSL_VERSION_NUMBER >= 0x1000100fL && !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) - // must be public because we want to use it from an OpenSSL callback - struct NPNContext { - NPNContext() : data(0), - len(0), - status(QSslConfiguration::NextProtocolNegotiationNone) - { } - unsigned char *data; - unsigned short len; - QSslConfiguration::NextProtocolNegotiationStatus status; - }; - NPNContext npnContext() const; -#endif // OPENSSL_VERSION_NUMBER >= 0x1000100fL ... - -protected: - QSslContext(); - -private: - SSL_CTX* ctx; - EVP_PKEY *pkey; - SSL_SESSION *session; - QByteArray m_sessionASN1; - int m_sessionTicketLifeTimeHint; - QSslError::SslError errorCode; - QString errorStr; - QSslConfiguration sslConfiguration; -#if OPENSSL_VERSION_NUMBER >= 0x1000100fL && !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) - QByteArray m_supportedNPNVersions; - NPNContext m_npnContext; -#endif // OPENSSL_VERSION_NUMBER >= 0x1000100fL ... -}; - -#endif // QT_NO_SSL - -QT_END_NAMESPACE - -#endif // QSSLCONTEXT_H diff --git a/src/network/ssl/qsslkey.cpp b/src/network/ssl/qsslkey.cpp deleted file mode 100644 index b43e28589f..0000000000 --- a/src/network/ssl/qsslkey.cpp +++ /dev/null @@ -1,537 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtNetwork module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -/*! - \class QSslKey - \brief The QSslKey class provides an interface for private and public keys. - \since 4.3 - - \reentrant - \ingroup network - \ingroup ssl - \ingroup shared - \inmodule QtNetwork - - QSslKey provides a simple API for managing keys. - - \sa QSslSocket, QSslCertificate, QSslCipher -*/ - -#include "qsslkey.h" -#include "qsslkey_p.h" -#include "qsslsocket_openssl_symbols_p.h" -#include "qsslsocket.h" -#include "qsslsocket_p.h" - -#include -#include -#include -#ifndef QT_NO_DEBUG_STREAM -#include -#endif - -QT_BEGIN_NAMESPACE - -/*! - \internal - */ -void QSslKeyPrivate::clear(bool deep) -{ - isNull = true; - if (!QSslSocket::supportsSsl()) - return; - if (rsa) { - if (deep) - q_RSA_free(rsa); - rsa = 0; - } - if (dsa) { - if (deep) - q_DSA_free(dsa); - dsa = 0; - } - if (opaque) { - if (deep) - q_EVP_PKEY_free(opaque); - opaque = 0; - } -} - -bool QSslKeyPrivate::fromEVP_PKEY(EVP_PKEY *pkey) -{ - if (pkey->type == EVP_PKEY_RSA) { - isNull = false; - algorithm = QSsl::Rsa; - type = QSsl::PrivateKey; - - rsa = q_RSA_new(); - memcpy(rsa, q_EVP_PKEY_get1_RSA(pkey), sizeof(RSA)); - - return true; - } - else if (pkey->type == EVP_PKEY_DSA) { - isNull = false; - algorithm = QSsl::Dsa; - type = QSsl::PrivateKey; - - dsa = q_DSA_new(); - memcpy(rsa, q_EVP_PKEY_get1_DSA(pkey), sizeof(DSA)); - - return true; - } - else { - // Unknown key type. This could be handled as opaque, but then - // we'd eventually leak memory since we wouldn't be able to free - // the underlying EVP_PKEY structure. For now, we won't support - // this. - } - - return false; -} - -/*! - \internal - - Allocates a new rsa or dsa struct and decodes \a pem into it - according to the current algorithm and type. - - If \a deepClear is true, the rsa/dsa struct is freed if it is was - already allocated, otherwise we "leak" memory (which is exactly - what we want for copy construction). - - If \a passPhrase is non-empty, it will be used for decrypting - \a pem. -*/ -void QSslKeyPrivate::decodePem(const QByteArray &pem, const QByteArray &passPhrase, - bool deepClear) -{ - if (pem.isEmpty()) - return; - - clear(deepClear); - - if (!QSslSocket::supportsSsl()) - return; - - BIO *bio = q_BIO_new_mem_buf(const_cast(pem.data()), pem.size()); - if (!bio) - return; - - void *phrase = (void *)passPhrase.constData(); - - if (algorithm == QSsl::Rsa) { - RSA *result = (type == QSsl::PublicKey) - ? q_PEM_read_bio_RSA_PUBKEY(bio, &rsa, 0, phrase) - : q_PEM_read_bio_RSAPrivateKey(bio, &rsa, 0, phrase); - if (rsa && rsa == result) - isNull = false; - } else { - DSA *result = (type == QSsl::PublicKey) - ? q_PEM_read_bio_DSA_PUBKEY(bio, &dsa, 0, phrase) - : q_PEM_read_bio_DSAPrivateKey(bio, &dsa, 0, phrase); - if (dsa && dsa == result) - isNull = false; - } - - q_BIO_free(bio); -} - -/*! - Constructs a null key. - - \sa isNull() -*/ -QSslKey::QSslKey() - : d(new QSslKeyPrivate) -{ -} - -/*! - \internal -*/ -QByteArray QSslKeyPrivate::pemHeader() const -{ - // ### use QByteArray::fromRawData() instead - if (type == QSsl::PublicKey) - return QByteArray("-----BEGIN PUBLIC KEY-----\n"); - else if (algorithm == QSsl::Rsa) - return QByteArray("-----BEGIN RSA PRIVATE KEY-----\n"); - return QByteArray("-----BEGIN DSA PRIVATE KEY-----\n"); -} - -/*! - \internal -*/ -QByteArray QSslKeyPrivate::pemFooter() const -{ - // ### use QByteArray::fromRawData() instead - if (type == QSsl::PublicKey) - return QByteArray("-----END PUBLIC KEY-----\n"); - else if (algorithm == QSsl::Rsa) - return QByteArray("-----END RSA PRIVATE KEY-----\n"); - return QByteArray("-----END DSA PRIVATE KEY-----\n"); -} - -/*! - \internal - - Returns a DER key formatted as PEM. -*/ -QByteArray QSslKeyPrivate::pemFromDer(const QByteArray &der) const -{ - QByteArray pem(der.toBase64()); - - const int lineWidth = 64; // RFC 1421 - const int newLines = pem.size() / lineWidth; - const bool rem = pem.size() % lineWidth; - - // ### optimize - for (int i = 0; i < newLines; ++i) - pem.insert((i + 1) * lineWidth + i, '\n'); - if (rem) - pem.append('\n'); // ### - - pem.prepend(pemHeader()); - pem.append(pemFooter()); - - return pem; -} - -/*! - \internal - - Returns a PEM key formatted as DER. -*/ -QByteArray QSslKeyPrivate::derFromPem(const QByteArray &pem) const -{ - const QByteArray header = pemHeader(); - const QByteArray footer = pemFooter(); - - QByteArray der(pem); - - const int headerIndex = der.indexOf(header); - const int footerIndex = der.indexOf(footer); - if (headerIndex == -1 || footerIndex == -1) - return QByteArray(); - - der = der.mid(headerIndex + header.size(), footerIndex - (headerIndex + header.size())); - - return QByteArray::fromBase64(der); // ignores newlines -} - -/*! - Constructs a QSslKey by decoding the string in the byte array - \a encoded using a specified \a algorithm and \a encoding format. - If the encoded key is encrypted, \a passPhrase is used to decrypt - it. \a type specifies whether the key is public or private. - - After construction, use isNull() to check if \a encoded contained - a valid key. -*/ -QSslKey::QSslKey(const QByteArray &encoded, QSsl::KeyAlgorithm algorithm, - QSsl::EncodingFormat encoding, QSsl::KeyType type, const QByteArray &passPhrase) - : d(new QSslKeyPrivate) -{ - d->type = type; - d->algorithm = algorithm; - d->decodePem((encoding == QSsl::Der) - ? d->pemFromDer(encoded) : encoded, - passPhrase); -} - -/*! - Constructs a QSslKey by reading and decoding data from a - \a device using a specified \a algorithm and \a encoding format. - If the encoded key is encrypted, \a passPhrase is used to decrypt - it. \a type specifies whether the key is public or private. - - After construction, use isNull() to check if \a device provided - a valid key. -*/ -QSslKey::QSslKey(QIODevice *device, QSsl::KeyAlgorithm algorithm, QSsl::EncodingFormat encoding, - QSsl::KeyType type, const QByteArray &passPhrase) - : d(new QSslKeyPrivate) -{ - QByteArray encoded; - if (device) - encoded = device->readAll(); - d->type = type; - d->algorithm = algorithm; - d->decodePem((encoding == QSsl::Der) ? - d->pemFromDer(encoded) : encoded, - passPhrase); -} - -/*! - \since 5.0 - Constructs a QSslKey from a valid native key \a handle. - \a type specifies whether the key is public or private. - - QSslKey will take ownership for this key and you must not - free the key using the native library. The algorithm used - when creating a key from a handle will always be QSsl::Opaque. -*/ -QSslKey::QSslKey(Qt::HANDLE handle, QSsl::KeyType type) - : d(new QSslKeyPrivate) -{ - d->opaque = reinterpret_cast(handle); - d->algorithm = QSsl::Opaque; - d->type = type; - d->isNull = !d->opaque; -} - -/*! - Constructs an identical copy of \a other. -*/ -QSslKey::QSslKey(const QSslKey &other) : d(other.d) -{ -} - -/*! - Destroys the QSslKey object. -*/ -QSslKey::~QSslKey() -{ -} - -/*! - Copies the contents of \a other into this key, making the two keys - identical. - - Returns a reference to this QSslKey. -*/ -QSslKey &QSslKey::operator=(const QSslKey &other) -{ - d = other.d; - return *this; -} - -/*! - \fn void QSslKey::swap(QSslKey &other) - \since 5.0 - - Swaps this ssl key with \a other. This function is very fast and - never fails. -*/ - -/*! - Returns \c true if this is a null key; otherwise false. - - \sa clear() -*/ -bool QSslKey::isNull() const -{ - return d->isNull; -} - -/*! - Clears the contents of this key, making it a null key. - - \sa isNull() -*/ -void QSslKey::clear() -{ - d = new QSslKeyPrivate; -} - -/*! - Returns the length of the key in bits, or -1 if the key is null. -*/ -int QSslKey::length() const -{ - if (d->isNull || d->algorithm == QSsl::Opaque) - return -1; - - return (d->algorithm == QSsl::Rsa) - ? q_BN_num_bits(d->rsa->n) : q_BN_num_bits(d->dsa->p); -} - -/*! - Returns the type of the key (i.e., PublicKey or PrivateKey). -*/ -QSsl::KeyType QSslKey::type() const -{ - return d->type; -} - -/*! - Returns the key algorithm. -*/ -QSsl::KeyAlgorithm QSslKey::algorithm() const -{ - return d->algorithm; -} - -/*! - Returns the key in DER encoding. The result is encrypted with - \a passPhrase if the key is a private key and \a passPhrase is - non-empty. -*/ -// ### autotest failure for non-empty passPhrase and private key -QByteArray QSslKey::toDer(const QByteArray &passPhrase) const -{ - if (d->isNull || d->algorithm == QSsl::Opaque) - return QByteArray(); - - return d->derFromPem(toPem(passPhrase)); -} - -/*! - Returns the key in PEM encoding. The result is encrypted with - \a passPhrase if the key is a private key and \a passPhrase is - non-empty. -*/ -QByteArray QSslKey::toPem(const QByteArray &passPhrase) const -{ - if (!QSslSocket::supportsSsl() || d->isNull || d->algorithm == QSsl::Opaque) - return QByteArray(); - - BIO *bio = q_BIO_new(q_BIO_s_mem()); - if (!bio) - return QByteArray(); - - bool fail = false; - - if (d->algorithm == QSsl::Rsa) { - if (d->type == QSsl::PublicKey) { - if (!q_PEM_write_bio_RSA_PUBKEY(bio, d->rsa)) - fail = true; - } else { - if (!q_PEM_write_bio_RSAPrivateKey( - bio, d->rsa, - // ### the cipher should be selectable in the API: - passPhrase.isEmpty() ? (const EVP_CIPHER *)0 : q_EVP_des_ede3_cbc(), - (uchar *)passPhrase.data(), passPhrase.size(), 0, 0)) { - fail = true; - } - } - } else { - if (d->type == QSsl::PublicKey) { - if (!q_PEM_write_bio_DSA_PUBKEY(bio, d->dsa)) - fail = true; - } else { - if (!q_PEM_write_bio_DSAPrivateKey( - bio, d->dsa, - // ### the cipher should be selectable in the API: - passPhrase.isEmpty() ? (const EVP_CIPHER *)0 : q_EVP_des_ede3_cbc(), - (uchar *)passPhrase.data(), passPhrase.size(), 0, 0)) { - fail = true; - } - } - } - - QByteArray pem; - if (!fail) { - char *data; - long size = q_BIO_get_mem_data(bio, &data); - pem = QByteArray(data, size); - } - q_BIO_free(bio); - return pem; -} - -/*! - Returns a pointer to the native key handle, if it is available; - otherwise a null pointer is returned. - - You can use this handle together with the native API to access - extended information about the key. - - \warning Use of this function has a high probability of being - non-portable, and its return value may vary across platforms, and - between minor Qt releases. -*/ -Qt::HANDLE QSslKey::handle() const -{ - switch (d->algorithm) { - case QSsl::Opaque: - return Qt::HANDLE(d->opaque); - case QSsl::Rsa: - return Qt::HANDLE(d->rsa); - case QSsl::Dsa: - return Qt::HANDLE(d->dsa); - default: - return Qt::HANDLE(NULL); - } -} - -/*! - Returns \c true if this key is equal to \a other; otherwise returns \c false. -*/ -bool QSslKey::operator==(const QSslKey &other) const -{ - if (isNull()) - return other.isNull(); - if (other.isNull()) - return isNull(); - if (algorithm() != other.algorithm()) - return false; - if (type() != other.type()) - return false; - if (length() != other.length()) - return false; - if (algorithm() == QSsl::Opaque) - return handle() == other.handle(); - return toDer() == other.toDer(); -} - -/*! \fn bool QSslKey::operator!=(const QSslKey &other) const - - Returns \c true if this key is not equal to key \a other; otherwise - returns \c false. -*/ - -#ifndef QT_NO_DEBUG_STREAM -class QDebug; -QDebug operator<<(QDebug debug, const QSslKey &key) -{ - debug << "QSslKey(" - << (key.type() == QSsl::PublicKey ? "PublicKey" : "PrivateKey") - << ", " << (key.algorithm() == QSsl::Opaque ? "OPAQUE" : - (key.algorithm() == QSsl::Rsa ? "RSA" : "DSA")) - << ", " << key.length() - << ')'; - return debug; -} -#endif - -QT_END_NAMESPACE diff --git a/src/network/ssl/qsslkey_openssl.cpp b/src/network/ssl/qsslkey_openssl.cpp new file mode 100644 index 0000000000..a6dab2ba38 --- /dev/null +++ b/src/network/ssl/qsslkey_openssl.cpp @@ -0,0 +1,218 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the QtNetwork module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + + +#include "qsslkey.h" +#include "qsslkey_p.h" +#include "qsslsocket_openssl_symbols_p.h" +#include "qsslsocket.h" +#include "qsslsocket_p.h" + +#include +#include +#include +#ifndef QT_NO_DEBUG_STREAM +#include +#endif + +QT_BEGIN_NAMESPACE + +void QSslKeyPrivate::clear(bool deep) +{ + isNull = true; + if (!QSslSocket::supportsSsl()) + return; + if (rsa) { + if (deep) + q_RSA_free(rsa); + rsa = 0; + } + if (dsa) { + if (deep) + q_DSA_free(dsa); + dsa = 0; + } + if (opaque) { + if (deep) + q_EVP_PKEY_free(opaque); + opaque = 0; + } +} + +bool QSslKeyPrivate::fromEVP_PKEY(EVP_PKEY *pkey) +{ + if (pkey->type == EVP_PKEY_RSA) { + isNull = false; + algorithm = QSsl::Rsa; + type = QSsl::PrivateKey; + + rsa = q_RSA_new(); + memcpy(rsa, q_EVP_PKEY_get1_RSA(pkey), sizeof(RSA)); + + return true; + } + else if (pkey->type == EVP_PKEY_DSA) { + isNull = false; + algorithm = QSsl::Dsa; + type = QSsl::PrivateKey; + + dsa = q_DSA_new(); + memcpy(rsa, q_EVP_PKEY_get1_DSA(pkey), sizeof(DSA)); + + return true; + } + else { + // Unknown key type. This could be handled as opaque, but then + // we'd eventually leak memory since we wouldn't be able to free + // the underlying EVP_PKEY structure. For now, we won't support + // this. + } + + return false; +} + +void QSslKeyPrivate::decodePem(const QByteArray &pem, const QByteArray &passPhrase, + bool deepClear) +{ + if (pem.isEmpty()) + return; + + clear(deepClear); + + if (!QSslSocket::supportsSsl()) + return; + + BIO *bio = q_BIO_new_mem_buf(const_cast(pem.data()), pem.size()); + if (!bio) + return; + + void *phrase = (void *)passPhrase.constData(); + + if (algorithm == QSsl::Rsa) { + RSA *result = (type == QSsl::PublicKey) + ? q_PEM_read_bio_RSA_PUBKEY(bio, &rsa, 0, phrase) + : q_PEM_read_bio_RSAPrivateKey(bio, &rsa, 0, phrase); + if (rsa && rsa == result) + isNull = false; + } else { + DSA *result = (type == QSsl::PublicKey) + ? q_PEM_read_bio_DSA_PUBKEY(bio, &dsa, 0, phrase) + : q_PEM_read_bio_DSAPrivateKey(bio, &dsa, 0, phrase); + if (dsa && dsa == result) + isNull = false; + } + + q_BIO_free(bio); +} + +int QSslKeyPrivate::length() const +{ + if (isNull || algorithm == QSsl::Opaque) + return -1; + + return (algorithm == QSsl::Rsa) + ? q_BN_num_bits(rsa->n) : q_BN_num_bits(dsa->p); +} + +QByteArray QSslKeyPrivate::toPem(const QByteArray &passPhrase) const +{ + if (!QSslSocket::supportsSsl() || isNull || algorithm == QSsl::Opaque) + return QByteArray(); + + BIO *bio = q_BIO_new(q_BIO_s_mem()); + if (!bio) + return QByteArray(); + + bool fail = false; + + if (algorithm == QSsl::Rsa) { + if (type == QSsl::PublicKey) { + if (!q_PEM_write_bio_RSA_PUBKEY(bio, rsa)) + fail = true; + } else { + if (!q_PEM_write_bio_RSAPrivateKey( + bio, rsa, + // ### the cipher should be selectable in the API: + passPhrase.isEmpty() ? (const EVP_CIPHER *)0 : q_EVP_des_ede3_cbc(), + (uchar *)passPhrase.data(), passPhrase.size(), 0, 0)) { + fail = true; + } + } + } else { + if (type == QSsl::PublicKey) { + if (!q_PEM_write_bio_DSA_PUBKEY(bio, dsa)) + fail = true; + } else { + if (!q_PEM_write_bio_DSAPrivateKey( + bio, dsa, + // ### the cipher should be selectable in the API: + passPhrase.isEmpty() ? (const EVP_CIPHER *)0 : q_EVP_des_ede3_cbc(), + (uchar *)passPhrase.data(), passPhrase.size(), 0, 0)) { + fail = true; + } + } + } + + QByteArray pem; + if (!fail) { + char *data; + long size = q_BIO_get_mem_data(bio, &data); + pem = QByteArray(data, size); + } + q_BIO_free(bio); + return pem; +} + +Qt::HANDLE QSslKeyPrivate::handle() const +{ + switch (algorithm) { + case QSsl::Opaque: + return Qt::HANDLE(opaque); + case QSsl::Rsa: + return Qt::HANDLE(rsa); + case QSsl::Dsa: + return Qt::HANDLE(dsa); + default: + return Qt::HANDLE(NULL); + } +} + +QT_END_NAMESPACE diff --git a/src/network/ssl/qsslkey_p.cpp b/src/network/ssl/qsslkey_p.cpp new file mode 100644 index 0000000000..c6e873dc49 --- /dev/null +++ b/src/network/ssl/qsslkey_p.cpp @@ -0,0 +1,396 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the QtNetwork module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + + +/*! + \class QSslKey + \brief The QSslKey class provides an interface for private and public keys. + \since 4.3 + + \reentrant + \ingroup network + \ingroup ssl + \ingroup shared + \inmodule QtNetwork + + QSslKey provides a simple API for managing keys. + + \sa QSslSocket, QSslCertificate, QSslCipher +*/ + +#include "qsslkey.h" +#include "qsslkey_p.h" +#include "qsslsocket.h" +#include "qsslsocket_p.h" + +#include +#include +#include +#ifndef QT_NO_DEBUG_STREAM +#include +#endif + +QT_BEGIN_NAMESPACE + +/*! + \fn void QSslKeyPrivate::clear(bool deep) + \internal + */ + +/*! + \fn void QSslKeyPrivate::decodePem(const QByteArray &pem, const QByteArray &passPhrase, + bool deepClear) + \internal + + Allocates a new rsa or dsa struct and decodes \a pem into it + according to the current algorithm and type. + + If \a deepClear is true, the rsa/dsa struct is freed if it is was + already allocated, otherwise we "leak" memory (which is exactly + what we want for copy construction). + + If \a passPhrase is non-empty, it will be used for decrypting + \a pem. +*/ + +/*! + Constructs a null key. + + \sa isNull() +*/ +QSslKey::QSslKey() + : d(new QSslKeyPrivate) +{ +} + +/*! + \internal +*/ +QByteArray QSslKeyPrivate::pemHeader() const +{ + // ### use QByteArray::fromRawData() instead + if (type == QSsl::PublicKey) + return QByteArray("-----BEGIN PUBLIC KEY-----\n"); + else if (algorithm == QSsl::Rsa) + return QByteArray("-----BEGIN RSA PRIVATE KEY-----\n"); + return QByteArray("-----BEGIN DSA PRIVATE KEY-----\n"); +} + +/*! + \internal +*/ +QByteArray QSslKeyPrivate::pemFooter() const +{ + // ### use QByteArray::fromRawData() instead + if (type == QSsl::PublicKey) + return QByteArray("-----END PUBLIC KEY-----\n"); + else if (algorithm == QSsl::Rsa) + return QByteArray("-----END RSA PRIVATE KEY-----\n"); + return QByteArray("-----END DSA PRIVATE KEY-----\n"); +} + +/*! + \internal + + Returns a DER key formatted as PEM. +*/ +QByteArray QSslKeyPrivate::pemFromDer(const QByteArray &der) const +{ + QByteArray pem(der.toBase64()); + + const int lineWidth = 64; // RFC 1421 + const int newLines = pem.size() / lineWidth; + const bool rem = pem.size() % lineWidth; + + // ### optimize + for (int i = 0; i < newLines; ++i) + pem.insert((i + 1) * lineWidth + i, '\n'); + if (rem) + pem.append('\n'); // ### + + pem.prepend(pemHeader()); + pem.append(pemFooter()); + + return pem; +} + +/*! + \internal + + Returns a PEM key formatted as DER. +*/ +QByteArray QSslKeyPrivate::derFromPem(const QByteArray &pem) const +{ + const QByteArray header = pemHeader(); + const QByteArray footer = pemFooter(); + + QByteArray der(pem); + + const int headerIndex = der.indexOf(header); + const int footerIndex = der.indexOf(footer); + if (headerIndex == -1 || footerIndex == -1) + return QByteArray(); + + der = der.mid(headerIndex + header.size(), footerIndex - (headerIndex + header.size())); + + return QByteArray::fromBase64(der); // ignores newlines +} + +/*! + Constructs a QSslKey by decoding the string in the byte array + \a encoded using a specified \a algorithm and \a encoding format. + If the encoded key is encrypted, \a passPhrase is used to decrypt + it. \a type specifies whether the key is public or private. + + After construction, use isNull() to check if \a encoded contained + a valid key. +*/ +QSslKey::QSslKey(const QByteArray &encoded, QSsl::KeyAlgorithm algorithm, + QSsl::EncodingFormat encoding, QSsl::KeyType type, const QByteArray &passPhrase) + : d(new QSslKeyPrivate) +{ + d->type = type; + d->algorithm = algorithm; + d->decodePem((encoding == QSsl::Der) + ? d->pemFromDer(encoded) : encoded, + passPhrase); +} + +/*! + Constructs a QSslKey by reading and decoding data from a + \a device using a specified \a algorithm and \a encoding format. + If the encoded key is encrypted, \a passPhrase is used to decrypt + it. \a type specifies whether the key is public or private. + + After construction, use isNull() to check if \a device provided + a valid key. +*/ +QSslKey::QSslKey(QIODevice *device, QSsl::KeyAlgorithm algorithm, QSsl::EncodingFormat encoding, + QSsl::KeyType type, const QByteArray &passPhrase) + : d(new QSslKeyPrivate) +{ + QByteArray encoded; + if (device) + encoded = device->readAll(); + d->type = type; + d->algorithm = algorithm; + d->decodePem((encoding == QSsl::Der) ? + d->pemFromDer(encoded) : encoded, + passPhrase); +} + +/*! + \since 5.0 + Constructs a QSslKey from a valid native key \a handle. + \a type specifies whether the key is public or private. + + QSslKey will take ownership for this key and you must not + free the key using the native library. The algorithm used + when creating a key from a handle will always be QSsl::Opaque. +*/ +QSslKey::QSslKey(Qt::HANDLE handle, QSsl::KeyType type) + : d(new QSslKeyPrivate) +{ + d->opaque = reinterpret_cast(handle); + d->algorithm = QSsl::Opaque; + d->type = type; + d->isNull = !d->opaque; +} + +/*! + Constructs an identical copy of \a other. +*/ +QSslKey::QSslKey(const QSslKey &other) : d(other.d) +{ +} + +/*! + Destroys the QSslKey object. +*/ +QSslKey::~QSslKey() +{ +} + +/*! + Copies the contents of \a other into this key, making the two keys + identical. + + Returns a reference to this QSslKey. +*/ +QSslKey &QSslKey::operator=(const QSslKey &other) +{ + d = other.d; + return *this; +} + +/*! + \fn void QSslKey::swap(QSslKey &other) + \since 5.0 + + Swaps this ssl key with \a other. This function is very fast and + never fails. +*/ + +/*! + Returns \c true if this is a null key; otherwise false. + + \sa clear() +*/ +bool QSslKey::isNull() const +{ + return d->isNull; +} + +/*! + Clears the contents of this key, making it a null key. + + \sa isNull() +*/ +void QSslKey::clear() +{ + d = new QSslKeyPrivate; +} + +/*! + Returns the length of the key in bits, or -1 if the key is null. +*/ +int QSslKey::length() const +{ + return d->length(); +} + +/*! + Returns the type of the key (i.e., PublicKey or PrivateKey). +*/ +QSsl::KeyType QSslKey::type() const +{ + return d->type; +} + +/*! + Returns the key algorithm. +*/ +QSsl::KeyAlgorithm QSslKey::algorithm() const +{ + return d->algorithm; +} + +/*! + Returns the key in DER encoding. The result is encrypted with + \a passPhrase if the key is a private key and \a passPhrase is + non-empty. +*/ +// ### autotest failure for non-empty passPhrase and private key +QByteArray QSslKey::toDer(const QByteArray &passPhrase) const +{ + if (d->isNull || d->algorithm == QSsl::Opaque) + return QByteArray(); + + return d->derFromPem(toPem(passPhrase)); +} + +/*! + Returns the key in PEM encoding. The result is encrypted with + \a passPhrase if the key is a private key and \a passPhrase is + non-empty. +*/ +QByteArray QSslKey::toPem(const QByteArray &passPhrase) const +{ + return d->toPem(passPhrase); +} + +/*! + Returns a pointer to the native key handle, if it is available; + otherwise a null pointer is returned. + + You can use this handle together with the native API to access + extended information about the key. + + \warning Use of this function has a high probability of being + non-portable, and its return value may vary across platforms, and + between minor Qt releases. +*/ +Qt::HANDLE QSslKey::handle() const +{ + return d->handle(); +} + +/*! + Returns \c true if this key is equal to \a other; otherwise returns \c false. +*/ +bool QSslKey::operator==(const QSslKey &other) const +{ + if (isNull()) + return other.isNull(); + if (other.isNull()) + return isNull(); + if (algorithm() != other.algorithm()) + return false; + if (type() != other.type()) + return false; + if (length() != other.length()) + return false; + if (algorithm() == QSsl::Opaque) + return handle() == other.handle(); + return toDer() == other.toDer(); +} + +/*! \fn bool QSslKey::operator!=(const QSslKey &other) const + + Returns \c true if this key is not equal to key \a other; otherwise + returns \c false. +*/ + +#ifndef QT_NO_DEBUG_STREAM +class QDebug; +QDebug operator<<(QDebug debug, const QSslKey &key) +{ + debug << "QSslKey(" + << (key.type() == QSsl::PublicKey ? "PublicKey" : "PrivateKey") + << ", " << (key.algorithm() == QSsl::Opaque ? "OPAQUE" : + (key.algorithm() == QSsl::Rsa ? "RSA" : "DSA")) + << ", " << key.length() + << ')'; + return debug; +} +#endif + +QT_END_NAMESPACE diff --git a/src/network/ssl/qsslkey_p.h b/src/network/ssl/qsslkey_p.h index 658be85621..fd5f97c291 100644 --- a/src/network/ssl/qsslkey_p.h +++ b/src/network/ssl/qsslkey_p.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtNetwork module of the Qt Toolkit. @@ -40,8 +40,8 @@ ****************************************************************************/ -#ifndef QSSLKEY_P_H -#define QSSLKEY_P_H +#ifndef QSSLKEY_OPENSSL_P_H +#define QSSLKEY_OPENSSL_P_H #include "qsslkey.h" @@ -58,8 +58,14 @@ #include "qsslsocket_p.h" // includes wincrypt.h +#ifndef QT_NO_OPENSSL #include #include +#else +struct RSA; +struct DSA; +struct EVP_PKEY; +#endif QT_BEGIN_NAMESPACE @@ -87,6 +93,10 @@ public: QByteArray pemFromDer(const QByteArray &der) const; QByteArray derFromPem(const QByteArray &pem) const; + int length() const; + QByteArray toPem(const QByteArray &passPhrase) const; + Qt::HANDLE handle() const; + bool isNull; QSsl::KeyType type; QSsl::KeyAlgorithm algorithm; @@ -102,4 +112,4 @@ private: QT_END_NAMESPACE -#endif // QSSLKEY_P_H +#endif // QSSLKEY_OPENSSL_P_H diff --git a/src/network/ssl/qsslsocket.cpp b/src/network/ssl/qsslsocket.cpp index 8fd9114b2e..5020c8dc0c 100644 --- a/src/network/ssl/qsslsocket.cpp +++ b/src/network/ssl/qsslsocket.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Copyright (C) 2014 BlackBerry Limited. All rights reserved. ** Contact: http://www.qt-project.org/legal ** @@ -291,7 +291,9 @@ #include "qsslsocket.h" #include "qsslcipher.h" +#ifndef QT_NO_OPENSSL #include "qsslsocket_openssl_p.h" +#endif #include "qsslconfiguration_p.h" #include diff --git a/src/network/ssl/qsslsocket_p.h b/src/network/ssl/qsslsocket_p.h index 0033a46d98..a86fac8f94 100644 --- a/src/network/ssl/qsslsocket_p.h +++ b/src/network/ssl/qsslsocket_p.h @@ -59,7 +59,9 @@ #include #include "qsslkey.h" #include "qsslconfiguration_p.h" -#include +#ifndef QT_NO_OPENSSL +#include +#endif #include diff --git a/src/network/ssl/ssl.pri b/src/network/ssl/ssl.pri index eb8268515e..d7891b292a 100644 --- a/src/network/ssl/ssl.pri +++ b/src/network/ssl/ssl.pri @@ -3,30 +3,33 @@ contains(QT_CONFIG, openssl) | contains(QT_CONFIG, openssl-linked) { HEADERS += ssl/qssl.h \ ssl/qsslcertificate.h \ ssl/qsslcertificate_p.h \ - ssl/qsslconfiguration.h \ + ssl/qsslconfiguration.h \ ssl/qsslconfiguration_p.h \ ssl/qsslcipher.h \ ssl/qsslcipher_p.h \ ssl/qsslerror.h \ ssl/qsslkey.h \ + ssl/qsslkey_p.h \ ssl/qsslsocket.h \ ssl/qsslsocket_openssl_p.h \ ssl/qsslsocket_openssl_symbols_p.h \ ssl/qsslsocket_p.h \ ssl/qsslcertificateextension.h \ ssl/qsslcertificateextension_p.h \ - ssl/qsslcontext_p.h + ssl/qsslcontext_openssl_p.h SOURCES += ssl/qssl.cpp \ ssl/qsslcertificate.cpp \ - ssl/qsslconfiguration.cpp \ + ssl/qsslcertificate_openssl.cpp \ + ssl/qsslconfiguration.cpp \ ssl/qsslcipher.cpp \ + ssl/qsslkey_p.cpp \ ssl/qsslerror.cpp \ - ssl/qsslkey.cpp \ + ssl/qsslkey_openssl.cpp \ ssl/qsslsocket.cpp \ ssl/qsslsocket_openssl.cpp \ ssl/qsslsocket_openssl_symbols.cpp \ ssl/qsslcertificateextension.cpp \ - ssl/qsslcontext.cpp + ssl/qsslcontext_openssl.cpp android:!android-no-sdk: SOURCES += ssl/qsslsocket_openssl_android.cpp -- cgit v1.2.3