コード例 #1
0
void SettingsDialog::updateCert()
{
	QSslCertificate c = AccessCert::cert();
	if( !c.isNull() )
		d->p12Error->setText( tr("Issued to: %1\nValid to: %2").arg( c.subjectInfo( QSslCertificate::CommonName ), c.expiryDate().toString("dd.MM.yyyy") ) );
	else
		d->p12Error->setText( tr("Server access certificate is not installed."));
	d->showP12Cert->setEnabled( !c.isNull() );
	d->showP12Cert->setProperty( "cert", QVariant::fromValue( c ) );
}
コード例 #2
0
void SettingsDialog::updateCert()
{
	QSslCertificate c = AccessCert::cert();
	if( !c.isNull() )
		d->p12Error->setText( tr("Issued to: %1<br />Valid to: %2 %3")
			.arg( SslCertificate(c).subjectInfo( QSslCertificate::CommonName ) )
			.arg( c.expiryDate().toString("dd.MM.yyyy") )
			.arg( !c.isValid() ? "<font color='red'>(" + tr("expired") + ")</font>" : "" ) );
	else
		d->p12Error->setText( "<b>" + tr("Server access certificate is not installed.") + "</b>" );
	d->showP12Cert->setEnabled( !c.isNull() );
	d->showP12Cert->setProperty( "cert", QVariant::fromValue( c ) );
}
コード例 #3
0
ファイル: Connection.cpp プロジェクト: Acidburn0zzz/mumble
QList<QSslCertificate> Connection::peerCertificateChain() const {
	const QSslCertificate cert = qtsSocket->peerCertificate();
	if (cert.isNull())
		return QList<QSslCertificate>();
	else
		return qtsSocket->peerCertificateChain() << cert;
}
コード例 #4
0
ファイル: Cert.cpp プロジェクト: davidebeatrici/mumble
bool Server::isKeyForCert(const QSslKey &key, const QSslCertificate &cert) {
	if (key.isNull() || cert.isNull() || (key.type() != QSsl::PrivateKey))
		return false;

	QByteArray qbaKey = key.toDer();
	QByteArray qbaCert = cert.toDer();

	X509 *x509 = NULL;
	EVP_PKEY *pkey = NULL;
	BIO *mem = NULL;

	mem = BIO_new_mem_buf(qbaKey.data(), qbaKey.size());
	Q_UNUSED(BIO_set_close(mem, BIO_NOCLOSE));
	pkey = d2i_PrivateKey_bio(mem, NULL);
	BIO_free(mem);

	mem = BIO_new_mem_buf(qbaCert.data(), qbaCert.size());
	Q_UNUSED(BIO_set_close(mem, BIO_NOCLOSE));
	x509 = d2i_X509_bio(mem, NULL);
	BIO_free(mem);
	mem = NULL;

	if (x509 && pkey && X509_check_private_key(x509, pkey)) {
		EVP_PKEY_free(pkey);
		X509_free(x509);
		return true;
	}

	if (pkey)
		EVP_PKEY_free(pkey);
	if (x509)
		X509_free(x509);
	return false;
}
コード例 #5
0
ファイル: fvupdater.cpp プロジェクト: macressler/hifi
bool FvUpdater::checkSslFingerPrint(QUrl urltoCheck)
{
	if(urltoCheck.scheme()!="https")
	{
		qWarning()<<tr("SSL fingerprint check: The url %1 is not a ssl connection!").arg(urltoCheck.toString());
		return false;
	}

	QSslSocket *socket = new QSslSocket(this);
	socket->connectToHostEncrypted(urltoCheck.host(), 443);
	if( !socket->waitForEncrypted(1000))	// waits until ssl emits encrypted(), max 1000msecs
	{
		qWarning()<<"SSL fingerprint check: Unable to connect SSL server: "<<socket->sslErrors();
		return false;
	}

	QSslCertificate cert = socket->peerCertificate();

	if(cert.isNull())
	{
		qWarning()<<"SSL fingerprint check: Unable to retrieve SSL server certificate.";
		return false;
	}

	// COmpare digests
	if(cert.digest().toHex() != m_requiredSslFingerprint)
	{
		qWarning()<<"SSL fingerprint check: FINGERPRINT MISMATCH! Server digest="<<cert.digest().toHex()<<", requiered ssl digest="<<m_requiredSslFingerprint;
		return false;
	}
	
	return true;
}
コード例 #6
0
ファイル: qgsauthconfig.cpp プロジェクト: GeoCat/QGIS
void QgsPkiBundle::setClientCert( const QSslCertificate &cert )
{
  mCert.clear();
  if ( !cert.isNull() )
  {
    mCert = cert;
  }
}
コード例 #7
0
bool InstallChecker::verifyPackage( const QString &filePath, bool )
{
	QProcess proc;
	proc.start( "hdiutil", QStringList() << "verify" << filePath );
	proc.waitForFinished();
	if( proc.exitCode() )
		return false;

	QString path = mountPackage( filePath );
	if( path.isEmpty() )
		return false;

	xar_t xar = xar_open( path.toUtf8().constData(), 0 );
	if( !xar )
		return false;

	QSslCertificate cert;
	xar_signature_t sig = xar_signature_first( xar );
	int32_t count = xar_signature_get_x509certificate_count( sig );
	for( int32_t i = 0; i < count; ++i )
	{
		uint32_t size = 0;
		const uint8_t *data = 0;
		if( xar_signature_get_x509certificate_data( sig, i, &data, &size ) )
			continue;
		QSslCertificate c( QByteArray( (const char*)data, size ), QSsl::Der );
#if QT_VERSION >= 0x050000
		QString cn = c.subjectInfo( QSslCertificate::CommonName ).value(0);
#else
		QString cn = c.subjectInfo( QSslCertificate::CommonName );
#endif
		if( cn == "Estonian Informatics Centre" ||
			cn == "Developer ID Installer: Riigi Infosüsteemi Amet" )
			cert = c;
	}

	if( cert.isNull() )
	{
		xar_close( xar );
		return false;
	}

	uint8_t *data = 0, *signature = 0;
	uint32_t dataSize = 0, signatureSize = 0;
	off_t offset = 0;
	if( xar_signature_copy_signed_data( sig, &data, &dataSize, &signature, &signatureSize, &offset ) )
	{
		xar_close( xar );
		return false;
	}

	int result = RSA_verify( NID_sha1, data, dataSize, signature, signatureSize, (RSA*)cert.publicKey().handle() );
	xar_close( xar );
	free( data );
	free( signature );

	return result;
}
コード例 #8
0
ファイル: Pastebin.cpp プロジェクト: dkonigsberg/LogicPaste
void Pastebin::onSslErrors(QNetworkReply *reply, const QList<QSslError> &errors)
{
    QStringList ignoreCerts = AppSettings::instance()->ignoreErrorCerts();

    QList<QSslError> ignoreErrors;
    QList<QSslError> promptErrors;
    QSslCertificate cert;
    QStringList errorStrings;
    foreach(const QSslError &error, errors) {
        if(ignoreCerts.contains(QString(error.certificate().serialNumber()))) {
            ignoreErrors.append(error);
        }
        else {
            promptErrors.append(error);
            if(cert.isNull()) {
                cert = error.certificate();
            }
            errorStrings << error.errorString();
        }
    }

    if(!ignoreErrors.isEmpty()) {
        reply->ignoreSslErrors(ignoreErrors);
    }

    if(!promptErrors.isEmpty()) {
        QString bodyText = tr(
            "Issued to: %1\n"
            "Serial number: %2\n"
            "Issued by: %3\n"
            "Effective: %4\n"
            "Expires: %5\n"
            "\n%6\n\n"
            "Ignore this error?")
            .arg(cert.subjectInfo(QSslCertificate::CommonName))
            .arg(QString(cert.serialNumber()))
            .arg(cert.issuerInfo(QSslCertificate::CommonName))
            .arg(cert.effectiveDate().toLocalTime().toString(Qt::SystemLocaleShortDate))
            .arg(cert.expiryDate().toLocalTime().toString(Qt::SystemLocaleShortDate))
            .arg(errorStrings.join("\n"));

        bb::system::SystemDialog dialog(tr("Yes"), tr("Always"), tr("No"));
        dialog.setTitle(tr("SSL Error"));
        dialog.setBody(bodyText);
        bb::system::SystemUiResult::Type result = dialog.exec();

        if(result == bb::system::SystemUiResult::ConfirmButtonSelection
            || result == bb::system::SystemUiResult::CustomButtonSelection) {
            reply->ignoreSslErrors(promptErrors);

            if(result == bb::system::SystemUiResult::CustomButtonSelection) {
                ignoreCerts << QString(cert.serialNumber());
                AppSettings::instance()->setIgnoreErrorCerts(ignoreCerts);
            }
        }
    }
}
コード例 #9
0
ファイル: sslConnect.cpp プロジェクト: Krabi/idkaart_public
void SSLConnect::setToken( const QSslCertificate &cert, Qt::HANDLE key )
{
	if( !d->ssl )
		return d->setError( tr("SSL context is missing") );
	if( cert.isNull() )
		return d->setError( tr("Certificate is empty") );
	if( !SSL_use_certificate( d->ssl, X509_dup( (X509*)cert.handle() ) ) ||
		!SSL_use_PrivateKey( d->ssl, (EVP_PKEY*)key ) )
		d->setError();
}
コード例 #10
0
void SeafileApiClient::onSslErrors(const QList<QSslError>& errors)
{
    QUrl url = reply_->url();
    QSslCertificate cert = reply_->sslConfiguration().peerCertificate();
    if (cert.isNull()) {
        // The server has no ssl certificate, we do nothing and let the
        // request fail
        qDebug("the certificate for %s is null", url.toString().toUtf8().data());
        return;
    }

    CertsManager *mgr = seafApplet->certsManager();

    QSslCertificate saved_cert = mgr->getCertificate(url.toString());
    if (saved_cert.isNull()) {
        // This is the first time when the client connects to the server.
        QString question = tr("<b>Warning:</b> The ssl certificate of this server is not trusted, proceed anyway?");
        if (seafApplet->yesOrNoBox(question)) {
            mgr->saveCertificate(url, cert);
            reply_->ignoreSslErrors();
        }

        return;
    } else if (saved_cert == cert) {
        // The user has choosen to trust the certificate before
        reply_->ignoreSslErrors();
        return;
    } else {
        /**
         * The cert which the user had chosen to trust has been changed. It
         * may be either:
         *
         * 1. The server has changed its ssl certificate
         * 2. The user's connection is under security attack
         *
         * Anyway, we'll prompt the user
         */

        SslConfirmDialog dialog(url, seafApplet->mainWindow());
        if (dialog.exec() == QDialog::Accepted) {
            reply_->ignoreSslErrors();
            if (dialog.rememberChoice()) {
                mgr->saveCertificate(url, cert);
            }
        } else {
            reply_->abort();
        }
        return;
    }

    // SslConfirmDialog *dialog = new SslConfirmDialog(url, cert, errors, seafApplet->mainWindow());
    // dialog->show();
    // dialog->raise();
    // dialog->activateWindow();
}
コード例 #11
0
ファイル: browserwidget.cpp プロジェクト: gabrys/ffbrowser
void BrowserWidget::sslErrors(QNetworkReply *reply, const QList<QSslError> &sslErrors) {
    QSslCertificate sslCert;
    if (sslErrors.count() == 1) {
        sslCert = sslErrors[0].certificate();
        if (! sslCert.isNull() && acceptedSslCerts.contains(sslCert)) {
            reply->ignoreSslErrors();
            return;
        }
    }
    QString msg = "<qt>There is a problem with the site's certificate:<ul>";
    for (int i = 0; i < sslErrors.count(); i++) {
        msg += "<li>" + sslErrors[i].errorString() + "</li>";
    }
    msg += "</ul>Do you want to ignore these errors?</qt>";
    if (QMessageBox::warning(this, "SSL Errors", msg, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) {
        if (! sslCert.isNull() && ! acceptedSslCerts.contains(sslCert)) {
            acceptedSslCerts.append(QSslCertificate(sslCert));
        }
        reply->ignoreSslErrors();
    }
}
コード例 #12
0
ファイル: tasks.cpp プロジェクト: XilongPei/seafile-client
void FileServerTask::onSslErrors(const QList<QSslError>& errors)
{
    if (canceled_) {
        return;
    }
    QUrl url = reply_->url();
    QSslCertificate cert = reply_->sslConfiguration().peerCertificate();
    CertsManager *mgr = seafApplet->certsManager();
    if (!cert.isNull() && cert == mgr->getCertificate(url.toString())) {
        reply_->ignoreSslErrors();
        return;
    }
}
コード例 #13
0
QgsAuthSslConfigWidget::QgsAuthSslConfigWidget( QWidget *parent,
    const QSslCertificate& cert,
    const QString &hostport,
    const QList<QSslCertificate> &connectionCAs )
    : QWidget( parent )
    , mCert( nullptr )
    , mConnectionCAs( connectionCAs )
    , mProtocolItem( nullptr )
    , mProtocolCmbBx( nullptr )
    , mIgnoreErrorsItem( nullptr )
    , mVerifyModeItem( nullptr )
    , mVerifyPeerCmbBx( nullptr )
    , mVerifyDepthItem( nullptr )
    , mVerifyDepthSpnBx( nullptr )
    , mCanSave( false )
    , mDisabled( false )
    , mAuthNotifyLayout( nullptr )
    , mAuthNotify( nullptr )
{
  if ( QgsAuthManager::instance()->isDisabled() )
  {
    mDisabled = true;
    mAuthNotifyLayout = new QVBoxLayout;
    this->setLayout( mAuthNotifyLayout );
    mAuthNotify = new QLabel( QgsAuthManager::instance()->disabledMessage(), this );
    mAuthNotifyLayout->addWidget( mAuthNotify );
  }
  else
  {
    setupUi( this );

    connect( grpbxSslConfig, SIGNAL( toggled( bool ) ), this, SIGNAL( configEnabledChanged( bool ) ) );
    connect( this, SIGNAL( configEnabledChanged( bool ) ), this, SLOT( readyToSave() ) );
    connect( this, SIGNAL( hostPortValidityChanged( bool ) ), this, SLOT( readyToSave() ) );

    setUpSslConfigTree();

    lblLoadedConfig->setVisible( false );
    lblLoadedConfig->setText( QLatin1String( "" ) );

    connect( leHost, SIGNAL( textChanged( QString ) ),
             this, SLOT( validateHostPortText( QString ) ) );

    if ( !cert.isNull() )
    {
      setSslCertificate( cert, hostport );
    }
  }
}
コード例 #14
0
QSslCertificate IdentityEditWidget::certByFilename(const QString &filename)
{
    QSslCertificate cert;
    QFile certFile(filename);
    certFile.open(QIODevice::ReadOnly);
    QByteArray certRaw = certFile.read(2 << 20);
    certFile.close();

    for (int i = 0; i < 2; i++) {
        cert = QSslCertificate(certRaw, (QSsl::EncodingFormat)i);
        if (!cert.isNull())
            break;
    }
    return cert;
}
コード例 #15
0
void SslCertificateMonitor::socketReady(QObject *sockobj)
{
    QSslSocket *sock = qobject_cast<QSslSocket *>(sockobj);
    if (!sock)
        return;

    QString peerName = sock->peerName();
    QSslCertificate certificate = sock->peerCertificate();

    if (*(d->acceptedCache.object(peerName)) == certificate)
        return; // Fast path for most recently accepted certificates

    // Have we been here before?
    QSslCertificate previousCertificate = cachedCertificate(peerName);

    if (!previousCertificate.isNull()) {
        if (certificate == previousCertificate) {
            // We need to add the certificate to the cache here as well as when we add to
            // the on-disk cache so that we don't hit the disk again for this site.
            d->acceptedCache.insert(peerName,new QSslCertificate(certificate));
            return; // All is well
        }

        // Cert has changed
        QString message = evaluateCertificateChange( peerName, previousCertificate,
                                                     certificate, sock->sslErrors().isEmpty() );

        d->acceptCurrent = false;
        emit certificateWarning(sock, message);
    }
    else {
        // The certificate is new. We don't show anything to user because then
        // we're simply training them to click through our warning message without
        // thinking.
        d->acceptCurrent = true;
    }

    // If the user has chosen to accept the certificate or the certficate is new
    // then we store the updated entry.
    if (d->acceptCurrent) {
        d->acceptedCache.insert(peerName,new QSslCertificate(certificate));
        addCertificate(peerName, certificate);
    }
    else {
        // Certficate has been considered dangerous by the user
        sock->abort();
    }
}
コード例 #16
0
void QgsAuthSslErrorsDialog::showCertificateChainInfo()
{
  QList<QSslCertificate> peerchain( mSslConfiguration.peerCertificateChain() );

  if ( !peerchain.isEmpty() )
  {
    QSslCertificate cert = peerchain.takeFirst();
    if ( !cert.isNull() )
    {
      QgsAuthCertInfoDialog *dlg = new QgsAuthCertInfoDialog( cert, false, this, peerchain );
      dlg->setWindowModality( Qt::WindowModal );
      dlg->resize( 675, 500 );
      dlg->exec();
      dlg->deleteLater();
    }
  }
}
コード例 #17
0
void IdentityEditWidget::showCertState(const QSslCertificate &cert)
{
    if (cert.isNull()) {
        ui.certOrgLabel->setText(tr("No Certificate loaded"));
        ui.certCNameLabel->setText(tr("No Certificate loaded"));
        ui.clearOrLoadCertButton->setText(tr("Load"));
    }
    else {
#if QT_VERSION < 0x050000
        ui.certOrgLabel->setText(cert.subjectInfo(QSslCertificate::Organization));
        ui.certCNameLabel->setText(cert.subjectInfo(QSslCertificate::CommonName));
#else
        ui.certOrgLabel->setText(cert.subjectInfo(QSslCertificate::Organization).join(", "));
        ui.certCNameLabel->setText(cert.subjectInfo(QSslCertificate::CommonName).join(", "));
#endif
        ui.clearOrLoadCertButton->setText(tr("Clear"));
    }
    ui.certOrgLabel->setProperty("sslCert", cert.toPem());
}
コード例 #18
0
void CertificateDialog::exportCertificate()
{
	const QSslCertificate certificate(m_certificates.value(m_ui->chainItemView->currentIndex().data(Qt::UserRole).toInt()));

	if (certificate.isNull())
	{
		return;
	}

	QString filter;
	const QString path(QFileDialog::getSaveFileName(this, tr("Select File"), QStandardPaths::standardLocations(QStandardPaths::HomeLocation).value(0), Utils::formatFileTypes({tr("DER encoded X.509 certificates (*.der)"), tr("PEM encoded X.509 certificates (*.pem)"), tr("Text files (*.txt)")}), &filter));

	if (!path.isEmpty())
	{
		QFile file(path);

		if (!file.open(QIODevice::WriteOnly))
		{
			QMessageBox::critical(this, tr("Error"), tr("Failed to open file for writing."), QMessageBox::Close);

			return;
		}

		if (filter.contains(QLatin1String(".der")))
		{
			file.write(certificate.toDer());
		}
		else if (filter.contains(QLatin1String(".pem")))
		{
			file.write(certificate.toPem());
		}
		else
		{
			QTextStream stream(&file);
			stream << certificate.toText();
		}

		file.close();
	}
}
コード例 #19
0
ファイル: utils.cpp プロジェクト: beng81/seafile-client
QString dumpCertificate(const QSslCertificate &cert)
{
    if (cert.isNull())
      return "\n-\n";

    QString s = "\n";
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    s += cert.toText();
#else
    QString s_none = QObject::tr("<Not Part of Certificate>");
    #define CERTIFICATE_STR(x) ( ((x) == "" ) ? s_none : (x) )

    s += "Certificate:\n";
    s += "\nIssued To:\n";
    s += "CommonName(CN):             " + CERTIFICATE_STR(cert.subjectInfo(QSslCertificate::CommonName)) + "\n";
    s += "Organization(O):            " + CERTIFICATE_STR(cert.subjectInfo(QSslCertificate::Organization)) + "\n";
    s += "OrganizationalUnitName(OU): " + CERTIFICATE_STR(cert.subjectInfo(QSslCertificate::OrganizationalUnitName)) + "\n";
    s += "Serial Number:              " + dumpHexPresentation(cert.serialNumber()) + "\n";

    s += "\nIssued By:\n";
    s += "CommonName(CN):             " + CERTIFICATE_STR(cert.issuerInfo(QSslCertificate::CommonName)) + "\n";
    s += "Organization(O):            " + CERTIFICATE_STR(cert.issuerInfo(QSslCertificate::Organization)) + "\n";
    s += "OrganizationalUnitName(OU): " + CERTIFICATE_STR(cert.issuerInfo(QSslCertificate::OrganizationalUnitName)) + "\n";

    s += "\nPeriod Of Validity\n";
    s += "Begins On:    " + cert.effectiveDate().toString() + "\n";
    s += "Expires On:   " + cert.expiryDate().toString() + "\n";
    s += "IsValid:      " + (cert.isValid() ? QString("Yes") : QString("No")) + "\n";

    s += "\nFingerprints\n";
    s += "SHA1 Fingerprint:\n" + dumpCertificateFingerprint(cert, QCryptographicHash::Sha1) + "\n";
    s += "MD5 Fingerprint:\n" + dumpCertificateFingerprint(cert, QCryptographicHash::Md5) + "\n";
#endif

    s += "\n\n";
    s += cert.toPem();

    return s;
}
コード例 #20
0
void QgsAuthSslConfigWidget::setSslCertificate( const QSslCertificate &cert, const QString &hostport )
{
  if ( mDisabled )
  {
    return;
  }
  if ( cert.isNull() )
  {
    return;
  }
  mCert = cert;

  if ( !hostport.isEmpty() )
  {
    setSslHost( hostport );
  }

  QString sha( QgsAuthCertUtils::shaHexForCert( cert ) );
  QgsAuthConfigSslServer config(
    QgsAuthManager::instance()->getSslCertCustomConfig( sha, hostport.isEmpty() ? sslHost() : hostport ) );

  emit certFoundInAuthDatabase( !config.isNull() );

  lblLoadedConfig->setVisible( true );
  if ( !config.isNull() )
  {
    loadSslCustomConfig( config );
    leCommonName->setStyleSheet( QgsAuthGuiUtils::greenTextStyleSheet() );
  }
  else
  {
    lblLoadedConfig->setText( configNotFoundText_() );
    leCommonName->setText( QgsAuthCertUtils::resolvedCertName( mCert ) );
    leCommonName->setStyleSheet( QgsAuthGuiUtils::orangeTextStyleSheet() );
  }
  validateHostPortText( leHost->text() );
}
コード例 #21
0
void IdentityEditWidget::sslDropEvent(QDropEvent *event, bool isCert)
{
    QByteArray rawUris;
    if (event->mimeData()->hasFormat("text/uri-list"))
        rawUris = event->mimeData()->data("text/uri-list");
    else
        rawUris = event->mimeData()->data("text/uri");

    QTextStream uriStream(rawUris);
    QString filename = QUrl(uriStream.readLine()).toLocalFile();

    if (isCert) {
        QSslCertificate cert = certByFilename(filename);
        if (!cert.isNull())
            showCertState(cert);
    }
    else {
        QSslKey key = keyByFilename(filename);
        if (!key.isNull())
            showKeyState(key);
    }
    event->accept();
    emit widgetHasChanged();
}
コード例 #22
0
/*
 *  Webhook Functions
 */
bool TelegramBot::setHttpServerWebhook(qint16 port, QString pathCert, QString pathPrivateKey, int maxConnections, TelegramPollMessageTypes messageTypes)
{
    // try to acquire httpServer
    HttpServer* httpServer = 0;
    QSslCertificate cert;
    if(this->webHookWebServers.contains(port)) {
        // if existing webhook contains not the same privateKey, inform user and exit
        if(this->webHookWebServers.find(port).value()->isSamePrivateKey(pathPrivateKey)) {
            EXIT_FAILED("TelegramBot::setHttpServerWebhook - It's not possible to set multiple private keys for one webserver, webhook installation failed...")
        }
        httpServer = this->webHookWebServers.find(port).value();

        // add new cert
        cert = httpServer->addCert(pathCert);
        if(cert.isNull()) {
            EXIT_FAILED("TelegramBot::setHttpServerWebhook - Cert file %s is invalid, webhook installation failed...", qPrintable(pathCert))
        }
        if(cert.subjectInfo(QSslCertificate::CommonName).isEmpty()) {
            EXIT_FAILED("TelegramBot::setHttpServerWebhook - Cert don't contain a Common Name (CN), webhook installation failed...");
        }
    }

    // if no webserver exist, create it
    else {
コード例 #23
0
ファイル: sslwidget.cpp プロジェクト: Arakmar/rekonq
SSLWidget::SSLWidget(const QUrl &url, const WebSslInfo &info, QWidget *parent)
    : QMenu(parent)
    , m_url(url)
    , m_info(info)
{
    setAttribute(Qt::WA_DeleteOnClose);
    setMinimumWidth(400);

    QList<QSslCertificate> certList = m_info.certificateChain();
    QSslCertificate cert;
    if (!certList.isEmpty())
        cert = certList.first();

    QList<QStringList> certErrorList = SslInfoDialog::errorsFromString(m_info.certificateErrors());
    QStringList firstCertErrorList;
    if (!certErrorList.isEmpty())
        firstCertErrorList = certErrorList.first();

    QGridLayout *layout = new QGridLayout(this);

    QLabel *label;
    QLabel *imageLabel;

    int rows = 0;
    // ------------------------------------------------------------------------------------------------------
    imageLabel = new QLabel(this);
    layout->addWidget(imageLabel, rows , 0, Qt::AlignCenter);

    label = new QLabel(this);
    label->setWordWrap(true);
    label->setText(i18n("Identity"));
    QFont f1 = label->font();
    f1.setBold(true);
    label->setFont(f1);
    layout->addWidget(label, rows++, 1);

    label = new QLabel(this);
    label->setWordWrap(true);
    if (cert.isNull())
    {
        label->setText(i18n("Warning: this site is NOT carrying a certificate."));
        imageLabel->setPixmap(KIcon("security-low").pixmap(32));
        layout->addWidget(label, rows++, 1);
    }
    else
    {
        if (cert.isValid() && firstCertErrorList.isEmpty())
        {
            label->setText(i18n("The certificate for this site is valid and has been verified by:\n%1.",
                                Qt::escape(cert.issuerInfo(QSslCertificate::CommonName))));

            imageLabel->setPixmap(KIcon("security-high").pixmap(32));
        }
        else
        {
            QString c = QL1S("<ul>");
            Q_FOREACH(const QString & s, firstCertErrorList)
            {
                c += QL1S("<li>") + s + QL1S("</li>");
            }
            c += QL1S("</ul>");

            label->setText(i18n("The certificate for this site is NOT valid, for the following reasons:\n%1.", c));
            label->setTextFormat(Qt::RichText);
            imageLabel->setPixmap(KIcon("security-low").pixmap(32));
        }

        layout->addWidget(label, rows++, 1);

        label = new QLabel(this);
        label->setWordWrap(true);
        label->setText(QL1S("<a href=\"moresslinfos\">") + i18n("Certificate Information") + QL1S("</a>"));
        connect(label, SIGNAL(linkActivated(QString)), this, SLOT(showMoreSslInfos(QString)));
        layout->addWidget(label, rows++, 1);
    }
コード例 #24
0
void LeechCraft::SslErrorsDialog::PopulateTree (const QSslError& error)
{
	QTreeWidgetItem *item = new QTreeWidgetItem (Ui_.Errors_,
			QStringList ("Error:") << error.errorString ());

	QSslCertificate cer = error.certificate ();
	if (cer.isNull ())
	{
		new QTreeWidgetItem (item,
				QStringList (tr ("Certificate")) <<
					tr ("(No certificate available for this error)"));
		return;
	}

	new QTreeWidgetItem (item, QStringList (tr ("Valid:")) <<
				(cer.isValid () ? tr ("yes") : tr ("no")));
	new QTreeWidgetItem (item, QStringList (tr ("Effective date:")) <<
				cer.effectiveDate ().toString ());
	new QTreeWidgetItem (item, QStringList (tr ("Expiry date:")) <<
				cer.expiryDate ().toString ());
	new QTreeWidgetItem (item, QStringList (tr ("Version:")) <<
				cer.version ());
	new QTreeWidgetItem (item, QStringList (tr ("Serial number:")) <<
				cer.serialNumber ());
	new QTreeWidgetItem (item, QStringList (tr ("MD5 digest:")) <<
				cer.digest ().toHex ());
	new QTreeWidgetItem (item, QStringList (tr ("SHA1 digest:")) <<
				cer.digest (QCryptographicHash::Sha1).toHex ());

	QTreeWidgetItem *issuer = new QTreeWidgetItem (item,
			QStringList (tr ("Issuer info")));

	QString tmpString;
#if QT_VERSION >= 0x050000
	auto cvt = [] (const QStringList& list) { return list.join ("; "); };
#else
	auto cvt = [] (const QString& str) { return str; };
#endif
	tmpString = cvt (cer.issuerInfo (QSslCertificate::Organization));
	if (!tmpString.isEmpty ())
		new QTreeWidgetItem (issuer,
				QStringList (tr ("Organization:")) << tmpString);

	tmpString = cvt (cer.issuerInfo (QSslCertificate::CommonName));
	if (!tmpString.isEmpty ())
		new QTreeWidgetItem (issuer,
				QStringList (tr ("Common name:")) << tmpString);

	tmpString = cvt (cer.issuerInfo (QSslCertificate::LocalityName));
	if (!tmpString.isEmpty ())
		new QTreeWidgetItem (issuer,
				QStringList (tr ("Locality:")) << tmpString);

	tmpString = cvt (cer.issuerInfo (QSslCertificate::OrganizationalUnitName));
	if (!tmpString.isEmpty ())
		new QTreeWidgetItem (issuer,
				QStringList (tr ("Organizational unit name:")) << tmpString);

	tmpString = cvt (cer.issuerInfo (QSslCertificate::CountryName));
	if (!tmpString.isEmpty ())
		new QTreeWidgetItem (issuer,
				QStringList (tr ("Country name:")) << tmpString);

	tmpString = cvt (cer.issuerInfo (QSslCertificate::StateOrProvinceName));
	if (!tmpString.isEmpty ())
		new QTreeWidgetItem (issuer,
				QStringList (tr ("State or province name:")) << tmpString);

	QTreeWidgetItem *subject = new QTreeWidgetItem (item,
			QStringList (tr ("Subject info")));

	tmpString = cvt (cer.subjectInfo (QSslCertificate::Organization));
	if (!tmpString.isEmpty ())
		new QTreeWidgetItem (subject,
				QStringList (tr ("Organization:")) << tmpString);

	tmpString = cvt (cer.subjectInfo (QSslCertificate::CommonName));
	if (!tmpString.isEmpty ())
		new QTreeWidgetItem (subject,
				QStringList (tr ("Common name:")) << tmpString);

	tmpString = cvt (cer.subjectInfo (QSslCertificate::LocalityName));
	if (!tmpString.isEmpty ())
		new QTreeWidgetItem (subject,
				QStringList (tr ("Locality:")) << tmpString);

	tmpString = cvt (cer.subjectInfo (QSslCertificate::OrganizationalUnitName));
	if (!tmpString.isEmpty ())
		new QTreeWidgetItem (subject,
				QStringList (tr ("Organizational unit name:")) << tmpString);

	tmpString = cvt (cer.subjectInfo (QSslCertificate::CountryName));
	if (!tmpString.isEmpty ())
		new QTreeWidgetItem (subject,
				QStringList (tr ("Country name:")) << tmpString);

	tmpString = cvt (cer.subjectInfo (QSslCertificate::StateOrProvinceName));
	if (!tmpString.isEmpty ())
		new QTreeWidgetItem (subject,
				QStringList (tr ("State or province name:")) << tmpString);
}
コード例 #25
0
ファイル: sslserver.cpp プロジェクト: TC01/quassel
bool SslServer::setCertificate(const QString &path, const QString &keyPath)
{
    // Don't reset _isCertValid here, in case an older but valid certificate is still loaded.
    // Use temporary variables in order to avoid overwriting the existing certificates until
    // everything is confirmed good.
    QSslCertificate untestedCert;
    QList<QSslCertificate> untestedCA;
    QSslKey untestedKey;

    if (path.isEmpty())
        return false;

    QFile certFile(path);
    if (!certFile.exists()) {
        quWarning() << "SslServer: Certificate file" << qPrintable(path) << "does not exist";
        return false;
    }

    if (!certFile.open(QIODevice::ReadOnly)) {
        quWarning()
        << "SslServer: Failed to open certificate file" << qPrintable(path)
        << "error:" << certFile.error();
        return false;
    }

    QList<QSslCertificate> certList = QSslCertificate::fromDevice(&certFile);

    if (certList.isEmpty()) {
        quWarning() << "SslServer: Certificate file doesn't contain a certificate";
        return false;
    }

    untestedCert = certList[0];
    certList.removeFirst(); // remove server cert

    // store CA and intermediates certs
    untestedCA = certList;

    if (!certFile.reset()) {
        quWarning() << "SslServer: IO error reading certificate file";
        return false;
    }

    // load key from keyPath if it differs from path, otherwise load key from path
    if(path != keyPath) {
        QFile keyFile(keyPath);
        if(!keyFile.exists()) {
            quWarning() << "SslServer: Key file" << qPrintable(keyPath) << "does not exist";
            return false;
        }

        if (!keyFile.open(QIODevice::ReadOnly)) {
            quWarning()
            << "SslServer: Failed to open key file" << qPrintable(keyPath)
            << "error:" << keyFile.error();
            return false;
        }

        untestedKey = QSslKey(&keyFile, QSsl::Rsa);
        keyFile.close();
    } else {
        untestedKey = QSslKey(&certFile, QSsl::Rsa);
    }

    certFile.close();

    if (untestedCert.isNull()) {
        quWarning() << "SslServer:" << qPrintable(path) << "contains no certificate data";
        return false;
    }

    // We allow the core to offer SSL anyway, so no "return false" here. Client will warn about the cert being invalid.
    const QDateTime now = QDateTime::currentDateTime();
    if (now < untestedCert.effectiveDate())
        quWarning() << "SslServer: Certificate won't be valid before" << untestedCert.effectiveDate().toString();

    else if (now > untestedCert.expiryDate())
        quWarning() << "SslServer: Certificate expired on" << untestedCert.expiryDate().toString();

    else { // Qt4's isValid() checks for time range and blacklist; avoid a double warning, hence the else block
#if QT_VERSION < 0x050000
        if (!untestedCert.isValid())
#else
        if (untestedCert.isBlacklisted())
#endif
            quWarning() << "SslServer: Certificate blacklisted";
    }
    if (untestedKey.isNull()) {
        quWarning() << "SslServer:" << qPrintable(keyPath) << "contains no key data";
        return false;
    }

    _isCertValid = true;

    // All keys are valid, update the externally visible copy used for new connections.
    _cert = untestedCert;
    _ca = untestedCA;
    _key = untestedKey;

    return _isCertValid;
}
コード例 #26
0
ファイル: utils.cpp プロジェクト: beng81/seafile-client
QString dumpCertificateFingerprint(const QSslCertificate &cert, const QCryptographicHash::Algorithm &algorithm)
{
    if(cert.isNull())
      return "";
    return dumpHexPresentation(cert.digest(algorithm).toHex());
}
コード例 #27
0
ファイル: qgsauthpkipathsedit.cpp プロジェクト: dakcarto/QGIS
bool QgsAuthPkiPathsEdit::validateConfig()
{
  // required components
  QString certpath( lePkiPathsCert->text() );
  QString keypath( lePkiPathsKey->text() );

  bool certfound = QFile::exists( certpath );
  bool keyfound = QFile::exists( keypath );

  QgsAuthGuiUtils::fileFound( certpath.isEmpty() || certfound, lePkiPathsCert );
  QgsAuthGuiUtils::fileFound( keypath.isEmpty() || keyfound, lePkiPathsKey );

  if ( !certfound || !keyfound )
  {
    writePkiMessage( lePkiPathsMsg, tr( "Missing components" ), Invalid );
    return validityChange( false );
  }

  // check for issue date validity, then notify status
  QSslCertificate cert;
  QFile file( certpath );
  QFileInfo fileinfo( file );
  QString ext( fileinfo.fileName().replace( fileinfo.completeBaseName(), "" ).toLower() );
  if ( ext.isEmpty() )
  {
    writePkiMessage( lePkiPathsMsg, tr( "Certificate file has no extension" ), Invalid );
    return validityChange( false );
  }

  QFile::OpenMode openflags( QIODevice::ReadOnly );
  QSsl::EncodingFormat encformat( QSsl::Der );
  if ( ext == ".pem" )
  {
    openflags |= QIODevice::Text;
    encformat = QSsl::Pem;
  }

  if ( file.open( openflags ) )
  {
    cert = QSslCertificate( file.readAll(), encformat );
    file.close();
  }
  else
  {
    writePkiMessage( lePkiPathsMsg, tr( "Failed to read certificate file" ), Invalid );
    return validityChange( false );
  }

  if ( cert.isNull() )
  {
    writePkiMessage( lePkiPathsMsg, tr( "Failed to load certificate from file" ), Invalid );
    return validityChange( false );
  }

  bool certvalid = cert.isValid();
  QDateTime startdate( cert.effectiveDate() );
  QDateTime enddate( cert.expiryDate() );

  writePkiMessage( lePkiPathsMsg,
                   tr( "%1 thru %2" ).arg( startdate.toString(), enddate.toString() ),
                   ( certvalid ? Valid : Invalid ) );

  return validityChange( certvalid );
}