Exemple #1
0
// in Qt5, subjectInfo returns a QStringList(); turn this into a comma-separated string instead
QString SslInfoDlg::subjectInfo(const QSslCertificate &cert, QSslCertificate::SubjectInfo subjectInfo) const
{
#if QT_VERSION < 0x050000
    return cert.subjectInfo(subjectInfo);
#else
    return cert.subjectInfo(subjectInfo).join(", ");
#endif
}
QString subjectInfoHelper(const QSslCertificate& cert, const QByteArray &qa)
{
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
    return cert.subjectInfo(qa);
#else
    return cert.subjectInfo(qa).join(QLatin1Char('/'));
#endif
}
Exemple #3
0
void CertView::setCert(const QList<QSslCertificate> &cert) {
	qlCert = cert;

	if (qlCert.isEmpty()) {
		qlSubjectName->setText(QString());
		qlSubjectEmail->setText(QString());
		qlIssuerName->setText(QString());
		qlExpiry->setText(QString());
	} else {
		QSslCertificate qscCert = qlCert.at(0);

#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
		const QStringList &names = qscCert.subjectInfo(QSslCertificate::CommonName);
		QString name;
		if (names.count() > 0) {
			name = names.at(0);
		}

		QStringList emails = qscCert.subjectAlternativeNames().values(QSsl::EmailEntry);
#else
		const QString &name = qscCert.subjectInfo(QSslCertificate::CommonName);
		QStringList emails(qscCert.alternateSubjectNames().values(QSsl::EmailEntry));
#endif

		QString tmpName = name;
		tmpName = tmpName.replace(QLatin1String("\\x"), QLatin1String("%"));
		tmpName = QUrl::fromPercentEncoding(tmpName.toLatin1());

		qlSubjectName->setText(tmpName);

		if (emails.count() > 0)
			qlSubjectEmail->setText(emails.join(QLatin1String("\n")));
		else
			qlSubjectEmail->setText(tr("(none)"));

		if (qscCert.expiryDate() <= QDateTime::currentDateTime())
			qlExpiry->setText(QString::fromLatin1("<font color=\"red\"><b>%1</b></font>").arg(Qt::escape(qscCert.expiryDate().toString(Qt::SystemLocaleDate))));
		else
			qlExpiry->setText(qscCert.expiryDate().toString(Qt::SystemLocaleDate));

		if (qlCert.count() > 1)
			qscCert = qlCert.last();

#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
		const QStringList &issuerNames = qscCert.issuerInfo(QSslCertificate::CommonName);
		QString issuerName;
		if (issuerNames.count() > 0) {
			issuerName = issuerName.at(0);
		}
#else
		const QString &issuerName = qscCert.issuerInfo(QSslCertificate::CommonName);
#endif
		qlIssuerName->setText((issuerName == name) ? tr("Self-signed") : issuerName);
	}
}
QString CertificateInfoWidget::certificateItemText(const QSslCertificate &cert)
{
    QString commonName = cert.subjectInfo(QSslCertificate::CommonName);
    QString organization = cert.subjectInfo(QSslCertificate::Organization);

    if (commonName.isEmpty()) {
        return clearCertSpecialSymbols(organization);
    }

    return clearCertSpecialSymbols(commonName);
}
void PreferencesDialog::addClientCertToTable(const QString& path, const QSslCertificate& cert)
{
    // Do nothing if the file doesn't even exist
    if(!QFile::exists(path))
        return;

    // Add new row
    int row = ui->tableClientCerts->rowCount();
    ui->tableClientCerts->setRowCount(row + 1);

    // Fill row with data
    QTableWidgetItem* cert_file = new QTableWidgetItem(path);
    cert_file->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    ui->tableClientCerts->setItem(row, 0, cert_file);

    QTableWidgetItem* cert_subject_cn = new QTableWidgetItem(cert.subjectInfo(QSslCertificate::CommonName).at(0));
    cert_subject_cn->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    ui->tableClientCerts->setItem(row, 1, cert_subject_cn);

    QTableWidgetItem* cert_issuer_cn = new QTableWidgetItem(cert.issuerInfo(QSslCertificate::CommonName).at(0));
    cert_issuer_cn->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    ui->tableClientCerts->setItem(row, 2, cert_issuer_cn);

    QTableWidgetItem* cert_from = new QTableWidgetItem(cert.effectiveDate().toString());
    cert_from->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    ui->tableClientCerts->setItem(row, 3, cert_from);

    QTableWidgetItem* cert_to = new QTableWidgetItem(cert.expiryDate().toString());
    cert_to->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    ui->tableClientCerts->setItem(row, 4, cert_to);

    QTableWidgetItem* cert_serialno = new QTableWidgetItem(QString(cert.serialNumber()));
    cert_serialno->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    ui->tableClientCerts->setItem(row, 5, cert_serialno);
}
Exemple #6
0
void CertView::setCert(const QList<QSslCertificate> &cert) {
	qlCert = cert;

	if (qlCert.isEmpty()) {
		qlSubjectName->setText(QString());
		qlSubjectEmail->setText(QString());
		qlIssuerName->setText(QString());
	} else {
		QSslCertificate qscCert = qlCert.at(0);

		QStringList emails(qscCert.alternateSubjectNames().values(QSsl::EmailEntry));

		const QString &name = qscCert.subjectInfo(QSslCertificate::CommonName);

		QString tmpName = name;
		tmpName = tmpName.replace(QLatin1String("\\x"), QLatin1String("%"));
		tmpName = QUrl::fromPercentEncoding(tmpName.toLatin1());

		qlSubjectName->setText(tmpName);

		if (emails.count() > 0)
			qlSubjectEmail->setText(emails.join(QLatin1String("<br />")));
		else
			qlSubjectEmail->setText(tr("(none)"));

		if (qlCert.count() > 1)
			qscCert = qlCert.last();

		const QString &issuer = qscCert.issuerInfo(QSslCertificate::CommonName);
		qlIssuerName->setText((issuer == name) ? tr("Self-signed") : issuer);
	}
}
QString SslErrorDialog::certificateItemText(const QSslCertificate &cert)
{
#if QT_VERSION >= 0x050000
    QString commonName = cert.subjectInfo(QSslCertificate::CommonName).isEmpty() ? QString() : cert.subjectInfo(QSslCertificate::CommonName).at(0);
    QString organization = cert.subjectInfo(QSslCertificate::Organization).isEmpty() ? QString() : cert.subjectInfo(QSslCertificate::Organization).at(0);
#else
    QString commonName = cert.subjectInfo(QSslCertificate::CommonName);
    QString organization = cert.subjectInfo(QSslCertificate::Organization);
#endif

    if (commonName.isEmpty()) {
        return clearCertSpecialSymbols(organization);
    }

    return clearCertSpecialSymbols(commonName);
}
static QString certToFormattedString(QSslCertificate cert)
{
    QString resultstring = QLatin1String("<p>");
    QStringList tmplist;

    resultstring += cert.subjectInfo(QSslCertificate::CommonName);

    resultstring += QString::fromLatin1("<br/>Issuer: %1")
        .arg(cert.issuerInfo(QSslCertificate::CommonName));

    resultstring += QString::fromLatin1("<br/>Not valid before: %1<br/>Valid Until: %2")
        .arg(cert.effectiveDate().toString(Qt::ISODate))
        .arg(cert.expiryDate().toString(Qt::ISODate));

    QMultiMap<QSsl::AlternateNameEntryType, QString> names = cert.alternateSubjectNames();
    if (names.count() > 0) {
        tmplist = names.values(QSsl::DnsEntry);
        resultstring += QLatin1String("<br/>Alternate Names:<ul><li>")
            + tmplist.join(QLatin1String("</li><li>"))
            + QLatin1String("</li><</ul>");
    }

    resultstring += QLatin1String("</p>");

    return resultstring;
}
Exemple #9
0
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);
            }
        }
    }
}
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());
}
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 ) );
}
CertificateInfoWidget::CertificateInfoWidget(const QSslCertificate &cert, QWidget* parent)
    : QWidget(parent)
    , ui(new Ui::CertificateInfoWidget)
{
    ui->setupUi(this);

    //Issued to
    ui->issuedToCN->setText(showCertInfo(cert.subjectInfo(QSslCertificate::CommonName)));
    ui->issuedToO->setText(showCertInfo(cert.subjectInfo(QSslCertificate::Organization)));
    ui->issuedToOU->setText(showCertInfo(cert.subjectInfo(QSslCertificate::OrganizationalUnitName)));
    ui->issuedToSN->setText(showCertInfo(cert.serialNumber()));
    //Issued By
    ui->issuedByCN->setText(showCertInfo(cert.issuerInfo(QSslCertificate::CommonName)));
    ui->issuedByO->setText(showCertInfo(cert.issuerInfo(QSslCertificate::Organization)));
    ui->issuedByOU->setText(showCertInfo(cert.issuerInfo(QSslCertificate::OrganizationalUnitName)));
    //Validity
    ui->validityIssuedOn->setText(cert.effectiveDate().toString("dddd d. MMMM yyyy"));
    ui->validityExpiresOn->setText(cert.expiryDate().toString("dddd d. MMMM yyyy"));
}
bool QSslCertificatePrivate::isBlacklisted(const QSslCertificate &certificate)
{
    for (int a = 0; certificate_blacklist[a] != 0; a++) {
        QString blacklistedCommonName = QString::fromUtf8(certificate_blacklist[(a+1)]);
        if (certificate.serialNumber() == certificate_blacklist[a++] &&
                (certificate.subjectInfo(QSslCertificate::CommonName).contains(blacklistedCommonName) ||
                 certificate.issuerInfo(QSslCertificate::CommonName).contains(blacklistedCommonName)))
            return true;
    }
    return false;
}
void SslInfoDlg::setCurrentCert(int index)
{
    QSslCertificate cert = socket()->peerCertificateChain().at(index);
    ui.subjectCommonName->setText(cert.subjectInfo(QSslCertificate::CommonName));
    ui.subjectOrganization->setText(cert.subjectInfo(QSslCertificate::Organization));
    ui.subjectOrganizationalUnit->setText(cert.subjectInfo(QSslCertificate::OrganizationalUnitName));
    ui.subjectCountry->setText(cert.subjectInfo(QSslCertificate::CountryName));
    ui.subjectState->setText(cert.subjectInfo(QSslCertificate::StateOrProvinceName));
    ui.subjectCity->setText(cert.subjectInfo(QSslCertificate::LocalityName));

    ui.issuerCommonName->setText(cert.issuerInfo(QSslCertificate::CommonName));
    ui.issuerOrganization->setText(cert.issuerInfo(QSslCertificate::Organization));
    ui.issuerOrganizationalUnit->setText(cert.issuerInfo(QSslCertificate::OrganizationalUnitName));
    ui.issuerCountry->setText(cert.issuerInfo(QSslCertificate::CountryName));
    ui.issuerState->setText(cert.issuerInfo(QSslCertificate::StateOrProvinceName));
    ui.issuerCity->setText(cert.issuerInfo(QSslCertificate::LocalityName));

    if (socket()->sslErrors().isEmpty())
        ui.trusted->setText(tr("Yes"));
    else {
        QString errorString = tr("No, for the following reasons:<ul>");
        foreach(const QSslError &error, socket()->sslErrors())
        errorString += "<li>" + error.errorString() + "</li>";
        errorString += "</ul>";
        ui.trusted->setText(errorString);
    }

    ui.validity->setText(tr("%1 to %2").arg(cert.effectiveDate().date().toString(Qt::ISODate), cert.expiryDate().date().toString(Qt::ISODate)));
    ui.md5Digest->setText(prettyDigest(cert.digest(QCryptographicHash::Md5)));
    ui.sha1Digest->setText(prettyDigest(cert.digest(QCryptographicHash::Sha1)));
}
Exemple #15
0
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;
}
Exemple #16
0
void Connector::dumpCertificate( const QSslCertificate &cert )
{
    qDebug() << cert.toPem();

    qDebug() << "== Subject Info ==\b";
    qDebug() << "CommonName:\t\t" << cert.subjectInfo( QSslCertificate::CommonName );
    qDebug() << "Organization:\t\t" << cert.subjectInfo( QSslCertificate::Organization );
    qDebug() << "LocalityName:\t\t" << cert.subjectInfo( QSslCertificate::LocalityName );
    qDebug() << "OrganizationalUnitName:\t" << cert.subjectInfo( QSslCertificate::OrganizationalUnitName );
    qDebug() << "StateOrProvinceName:\t" << cert.subjectInfo( QSslCertificate::StateOrProvinceName );

    QMultiMap<QSsl::AlternateNameEntryType, QString> altNames = cert.alternateSubjectNames();
    if ( !altNames.isEmpty() ) {
        qDebug() << "Alternate Subject Names (DNS):";
        foreach (const QString &altName, altNames.values(QSsl::DnsEntry)) {
            qDebug() << altName;
        }

        qDebug() << "Alternate Subject Names (Email):";
        foreach (const QString &altName, altNames.values(QSsl::EmailEntry)) {
            qDebug() << altName;
        }
    }
QDebug operator<<(QDebug debug, const QSslCertificate &certificate)
{
    debug << "QSslCertificate("
          << certificate.version()
          << ',' << certificate.serialNumber()
          << ',' << certificate.digest().toBase64()
          << ',' << certificate.issuerInfo(QSslCertificate::Organization)
          << ',' << certificate.subjectInfo(QSslCertificate::Organization)
          << ',' << certificate.subjectAlternativeNames()
#ifndef QT_NO_DATESTRING
          << ',' << certificate.effectiveDate()
          << ',' << certificate.expiryDate()
#endif
          << ')';
    return debug;
}
QDebug operator<<(QDebug debug, const QSslCertificate &certificate)
{
    debug << "QSslCertificate("
          << certificate.version()
          << "," << certificate.serialNumber()
          << "," << certificate.digest()
          << "," << certificate.issuerInfo(QSslCertificate::Organization)
          << "," << certificate.subjectInfo(QSslCertificate::Organization)
          << "," << certificate.alternateSubjectNames()
#ifndef QT_NO_TEXTSTREAM
          << "," << certificate.effectiveDate()
          << "," << certificate.expiryDate()
#endif
          << ")";
    return debug;
}
/*
 *  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 {
void PreferencesDialog::loadSettings()
{
    ui->encodingComboBox->setCurrentIndex(ui->encodingComboBox->findText(Settings::getValue("db", "defaultencoding").toString(), Qt::MatchFixedString));
    ui->comboDefaultLocation->setCurrentIndex(Settings::getValue("db", "savedefaultlocation").toInt());
    ui->locationEdit->setText(Settings::getValue("db", "defaultlocation").toString());
    ui->checkUpdates->setChecked(Settings::getValue("checkversion", "enabled").toBool());

    ui->checkHideSchemaLinebreaks->setChecked(Settings::getValue("db", "hideschemalinebreaks").toBool());
    ui->foreignKeysCheckBox->setChecked(Settings::getValue("db", "foreignkeys").toBool());
    ui->spinPrefetchSize->setValue(Settings::getValue("db", "prefetchsize").toInt());
    ui->editDatabaseDefaultSqlText->setText(Settings::getValue("db", "defaultsqltext").toString());

    ui->defaultFieldTypeComboBox->addItems(DBBrowserDB::Datatypes);

    int defaultFieldTypeIndex = Settings::getValue("db", "defaultfieldtype").toInt();

    if (defaultFieldTypeIndex < DBBrowserDB::Datatypes.count())
    {
        ui->defaultFieldTypeComboBox->setCurrentIndex(defaultFieldTypeIndex);
    }

    // Gracefully handle the preferred Data Browser font not being available
    int matchingFont = ui->comboDataBrowserFont->findText(Settings::getValue("databrowser", "font").toString(), Qt::MatchExactly);
    if (matchingFont == -1)
        matchingFont = ui->comboDataBrowserFont->findText(Settings::getDefaultValue("databrowser", "font").toString());
    ui->comboDataBrowserFont->setCurrentIndex(matchingFont);

    ui->spinDataBrowserFontSize->setValue(Settings::getValue("databrowser", "fontsize").toInt());
    loadColorSetting(ui->fr_null_fg, "null_fg");
    loadColorSetting(ui->fr_null_bg, "null_bg");
    loadColorSetting(ui->fr_bin_fg, "bin_fg");
    loadColorSetting(ui->fr_bin_bg, "bin_bg");
    loadColorSetting(ui->fr_reg_fg, "reg_fg");
    loadColorSetting(ui->fr_reg_bg, "reg_bg");

    ui->spinSymbolLimit->setValue(Settings::getValue("databrowser", "symbol_limit").toInt());
    ui->spinCompleteThreshold->setValue(Settings::getValue("databrowser", "complete_threshold").toInt());
    ui->txtNull->setText(Settings::getValue("databrowser", "null_text").toString());
    ui->txtBlob->setText(Settings::getValue("databrowser", "blob_text").toString());
    ui->editFilterEscape->setText(Settings::getValue("databrowser", "filter_escape").toString());
    ui->spinFilterDelay->setValue(Settings::getValue("databrowser", "filter_delay").toInt());

    for(int i=0; i < ui->treeSyntaxHighlighting->topLevelItemCount(); ++i)
    {
        std::string name = ui->treeSyntaxHighlighting->topLevelItem(i)->text(0).toStdString();
        QString colorname = Settings::getValue("syntaxhighlighter", name + "_colour").toString();
        QColor color = QColor(colorname);
        ui->treeSyntaxHighlighting->topLevelItem(i)->setTextColor(2, color);
        ui->treeSyntaxHighlighting->topLevelItem(i)->setBackgroundColor(2, color);
        ui->treeSyntaxHighlighting->topLevelItem(i)->setText(2, colorname);
        if (name != "null" && name != "currentline"  && name != "background" && name != "foreground") {
            ui->treeSyntaxHighlighting->topLevelItem(i)->setCheckState(3, Settings::getValue("syntaxhighlighter", name + "_bold").toBool() ? Qt::Checked : Qt::Unchecked);
            ui->treeSyntaxHighlighting->topLevelItem(i)->setCheckState(4, Settings::getValue("syntaxhighlighter", name + "_italic").toBool() ? Qt::Checked : Qt::Unchecked);
            ui->treeSyntaxHighlighting->topLevelItem(i)->setCheckState(5, Settings::getValue("syntaxhighlighter", name + "_underline").toBool() ? Qt::Checked : Qt::Unchecked);
        }
    }

    // Remote settings
    ui->checkUseRemotes->setChecked(Settings::getValue("remote", "active").toBool());
    {
        auto ca_certs = static_cast<Application*>(qApp)->mainWindow()->getRemote().caCertificates();
        ui->tableCaCerts->setRowCount(ca_certs.size());
        for(int i=0;i<ca_certs.size();i++)
        {
            QSslCertificate cert = ca_certs.at(i);

            QTableWidgetItem* cert_cn = new QTableWidgetItem(cert.subjectInfo(QSslCertificate::CommonName).at(0));
            cert_cn->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
            ui->tableCaCerts->setItem(i, 0, cert_cn);

            QTableWidgetItem* cert_o = new QTableWidgetItem(cert.subjectInfo(QSslCertificate::Organization).at(0));
            cert_o->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
            ui->tableCaCerts->setItem(i, 1, cert_o);

            QTableWidgetItem* cert_from = new QTableWidgetItem(cert.effectiveDate().toString());
            cert_from->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
            ui->tableCaCerts->setItem(i, 2, cert_from);

            QTableWidgetItem* cert_to = new QTableWidgetItem(cert.expiryDate().toString());
            cert_to->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
            ui->tableCaCerts->setItem(i, 3, cert_to);

            QTableWidgetItem* cert_serialno = new QTableWidgetItem(QString(cert.serialNumber()));
            cert_serialno->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
            ui->tableCaCerts->setItem(i, 4, cert_serialno);
        }
    }
    {
        QStringList client_certs = Settings::getValue("remote", "client_certificates").toStringList();
        for(const QString& file : client_certs)
        {
            auto certs = QSslCertificate::fromPath(file);
            for(const QSslCertificate& cert : certs)
                addClientCertToTable(file, cert);
        }
    }
    ui->editRemoteCloneDirectory->setText(Settings::getValue("remote", "clonedirectory").toString());

    // Gracefully handle the preferred Editor font not being available
    matchingFont = ui->comboEditorFont->findText(Settings::getValue("editor", "font").toString(), Qt::MatchExactly);
    if (matchingFont == -1)
        matchingFont = ui->comboDataBrowserFont->findText(Settings::getDefaultValue("editor", "font").toString());
    ui->comboEditorFont->setCurrentIndex(matchingFont);

    ui->spinEditorFontSize->setValue(Settings::getValue("editor", "fontsize").toInt());
    ui->spinTabSize->setValue(Settings::getValue("editor", "tabsize").toInt());
    ui->spinLogFontSize->setValue(Settings::getValue("log", "fontsize").toInt());
    ui->wrapComboBox->setCurrentIndex(Settings::getValue("editor", "wrap_lines").toInt());
    ui->quoteComboBox->setCurrentIndex(Settings::getValue("editor", "identifier_quotes").toInt());
    ui->checkAutoCompletion->setChecked(Settings::getValue("editor", "auto_completion").toBool());
    ui->checkCompleteUpper->setEnabled(Settings::getValue("editor", "auto_completion").toBool());
    ui->checkCompleteUpper->setChecked(Settings::getValue("editor", "upper_keywords").toBool());
    ui->checkErrorIndicators->setChecked(Settings::getValue("editor", "error_indicators").toBool());
    ui->checkHorizontalTiling->setChecked(Settings::getValue("editor", "horizontal_tiling").toBool());

    ui->listExtensions->addItems(Settings::getValue("extensions", "list").toStringList());
    ui->checkRegexDisabled->setChecked(Settings::getValue("extensions", "disableregex").toBool());
    ui->checkAllowLoadExtension->setChecked(Settings::getValue("extensions", "enable_load_extension").toBool());
    fillLanguageBox();
    ui->appStyleCombo->setCurrentIndex(Settings::getValue("General", "appStyle").toInt());
    ui->toolbarStyleComboMain->setCurrentIndex(Settings::getValue("General", "toolbarStyle").toInt());
    ui->toolbarStyleComboStructure->setCurrentIndex(Settings::getValue("General", "toolbarStyleStructure").toInt());
    ui->toolbarStyleComboBrowse->setCurrentIndex(Settings::getValue("General", "toolbarStyleBrowse").toInt());
    ui->toolbarStyleComboSql->setCurrentIndex(Settings::getValue("General", "toolbarStyleSql").toInt());
    ui->toolbarStyleComboEditCell->setCurrentIndex(Settings::getValue("General", "toolbarStyleEditCell").toInt());
}
Exemple #21
0
static void ReportInvalidCertificate(const QSslCertificate& cert)
{
#if QT_VERSION < 0x050000
    qDebug() << QString("%1: Payment server found an invalid certificate: ").arg(__func__) << cert.serialNumber() << cert.subjectInfo(QSslCertificate::CommonName) << cert.subjectInfo(QSslCertificate::OrganizationalUnitName);
#else
    qDebug() << QString("%1: Payment server found an invalid certificate: ").arg(__func__) << cert.serialNumber() << cert.subjectInfo(QSslCertificate::CommonName) << cert.subjectInfo(QSslCertificate::DistinguishedNameQualifier) << cert.subjectInfo(QSslCertificate::OrganizationalUnitName);
#endif
}
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);
}
Exemple #23
0
WebsiteInformationDialog::WebsiteInformationDialog(WebWidget *widget, QWidget *parent) : Dialog(parent),
	m_sslInformation(widget->getSslInformation()),
	m_ui(new Ui::WebsiteInformationDialog)
{
	m_ui->setupUi(this);

	const WindowsManager::ContentStates state(widget->getContentState());
	const QString characterEncoding(widget->getCharacterEncoding());
	QString host(widget->getUrl().host());

	if (host.isEmpty())
	{
		host = (widget->getUrl().scheme() == QLatin1String("file") ? QLatin1String("localhost") : tr("(unknown)"));
	}

	if (state.testFlag(WindowsManager::FraudContentState))
	{
		m_ui->stateLabel->setText(tr("This website was marked as fraud."));
		m_ui->stateIconLabel->setPixmap(ThemesManager::getIcon(QLatin1String("badge-fraud"), false).pixmap(16, 16));
	}
	else if (state.testFlag(WindowsManager::TrustedContentState))
	{
		m_ui->stateLabel->setText(tr("Your connection with this website is private."));
		m_ui->stateIconLabel->setPixmap(ThemesManager::getIcon(QLatin1String("badge-trusted"), false).pixmap(16, 16));
	}
	else if (state.testFlag(WindowsManager::SecureContentState))
	{
		m_ui->stateLabel->setText(tr("Your connection with this website is private."));
		m_ui->stateIconLabel->setPixmap(ThemesManager::getIcon(QLatin1String("badge-secure"), false).pixmap(16, 16));
	}
	else if (state.testFlag(WindowsManager::RemoteContentState))
	{
		m_ui->stateLabel->setText(tr("Your connection with this website is not private."));
		m_ui->stateIconLabel->setPixmap(ThemesManager::getIcon(QLatin1String("badge-remote"), false).pixmap(16, 16));
	}
	else if (state.testFlag(WindowsManager::LocalContentState))
	{
		m_ui->stateLabel->setText(tr("You are viewing content from your local filesystem."));
		m_ui->stateIconLabel->setPixmap(ThemesManager::getIcon(QLatin1String("badge-local"), false).pixmap(16, 16));
	}
	else if (state.testFlag(WindowsManager::ApplicationContentState))
	{
		m_ui->stateLabel->setText(tr("You are viewing safe page from Otter Browser."));
		m_ui->stateIconLabel->setPixmap(ThemesManager::getIcon(QLatin1String("otter-browser"), false).pixmap(16, 16));
	}
	else
	{
		m_ui->stateLabel->setText(tr("No information."));
		m_ui->stateIconLabel->setPixmap(ThemesManager::getIcon(QLatin1String("badge-unknown"), false).pixmap(16, 16));
	}

	m_ui->hostLabel->setText(host);
	m_ui->addressLabelWidget->setText(widget->getUrl().toString());
	m_ui->titleLabelWidget->setText(widget->getTitle());
	m_ui->encodingLabelWidget->setText(characterEncoding.isEmpty() ? tr("unknown") : characterEncoding);
	m_ui->sizeLabelWidget->setText(Utils::formatUnit(widget->getPageInformation(WebWidget::BytesTotalInformation).toLongLong(), false, 1, true));
	m_ui->elementsLabelWidget->setText((widget->getPageInformation(WebWidget::RequestsBlockedInformation).toInt() > 0) ? tr("%1 (%n blocked)", "", widget->getPageInformation(WebWidget::RequestsBlockedInformation).toInt()).arg(widget->getPageInformation(WebWidget::RequestsStartedInformation).toInt()) : QString::number(widget->getPageInformation(WebWidget::RequestsStartedInformation).toInt()));
	m_ui->downloadDateLabelWidget->setText(Utils::formatDateTime(widget->getPageInformation(WebWidget::LoadingFinishedInformation).toDateTime()));

	const QString cookiesPolicy(widget->getOption(SettingsManager::Network_CookiesPolicyOption).toString());

	if (cookiesPolicy == QLatin1String("acceptExisting"))
	{
		m_ui->cookiesValueLabel->setText(tr("Only existing"));
	}
	else if (cookiesPolicy == QLatin1String("readOnly"))
	{
		m_ui->cookiesValueLabel->setText(tr("Only read existing"));
	}
	else if (cookiesPolicy == QLatin1String("ignore"))
	{
		m_ui->cookiesValueLabel->setText(tr("Never"));
	}
	else
	{
		m_ui->cookiesValueLabel->setText(tr("Always"));
	}

	const QString thirdPartyCookiesPolicy(widget->getOption(SettingsManager::Network_ThirdPartyCookiesPolicyOption).toString());

	if (thirdPartyCookiesPolicy == QLatin1String("acceptExisting"))
	{
		m_ui->thirdPartyCookiesValueLabel->setText(tr("Only existing"));
	}
	else if (thirdPartyCookiesPolicy == QLatin1String("ignore"))
	{
		m_ui->thirdPartyCookiesValueLabel->setText(tr("Never"));
	}
	else
	{
		m_ui->thirdPartyCookiesValueLabel->setText(tr("Always"));
	}

	const QString pluginsPolicy(widget->getOption(SettingsManager::Browser_EnablePluginsOption).toString());

	if (pluginsPolicy == QLatin1String("enabled"))
	{
		m_ui->pluginsValueLabel->setText(tr("Always"));
	}
	else if (pluginsPolicy == QLatin1String("disabled"))
	{
		m_ui->pluginsValueLabel->setText(tr("Never"));
	}
	else
	{
		m_ui->pluginsValueLabel->setText(tr("On demand"));
	}

	const QString imagesPolicy(widget->getOption(SettingsManager::Browser_EnableImagesOption).toString());

	if (imagesPolicy == QLatin1String("onlyCached"))
	{
		m_ui->imagesValueLabel->setText(tr("Only cached"));
	}
	else if (imagesPolicy == QLatin1String("disabled"))
	{
		m_ui->imagesValueLabel->setText(tr("Never"));
	}
	else
	{
		m_ui->imagesValueLabel->setText(tr("Always"));
	}

	m_ui->javascriptValueLabel->setText(widget->getOption(SettingsManager::Browser_EnableJavaScriptOption).toBool() ? tr("Always") : tr("Never"));

	const QString geolocationPolicy(widget->getOption(SettingsManager::Browser_EnableGeolocationOption).toString());

	if (geolocationPolicy == QLatin1String("enabled"))
	{
		m_ui->geolocationValueLabel->setText(tr("Always"));
	}
	else if (geolocationPolicy == QLatin1String("disabled"))
	{
		m_ui->geolocationValueLabel->setText(tr("Never"));
	}
	else
	{
		m_ui->geolocationValueLabel->setText(tr("Always ask"));
	}

	const QString fullScreenPolicy(widget->getOption(SettingsManager::Browser_EnableFullScreenOption).toString());

	if (fullScreenPolicy == QLatin1String("enabled"))
	{
		m_ui->fullScreenValueLabel->setText(tr("Always"));
	}
	else if (fullScreenPolicy == QLatin1String("disabled"))
	{
		m_ui->fullScreenValueLabel->setText(tr("Never"));
	}
	else
	{
		m_ui->fullScreenValueLabel->setText(tr("Always ask"));
	}

	const QString notificationsPolicy(widget->getOption(SettingsManager::Browser_EnableNotificationsOption).toString());

	if (notificationsPolicy == QLatin1String("enabled"))
	{
		m_ui->notificationsValueLabel->setText(tr("Always"));
	}
	else if (notificationsPolicy == QLatin1String("disabled"))
	{
		m_ui->notificationsValueLabel->setText(tr("Never"));
	}
	else
	{
		m_ui->notificationsValueLabel->setText(tr("Always ask"));
	}

	const QString popupsPolicy(widget->getOption(SettingsManager::Content_PopupsPolicyOption).toString());

	if (popupsPolicy == QLatin1String("openAll"))
	{
		m_ui->popupsValueLabel->setText(tr("Always"));
	}
	else if (popupsPolicy == QLatin1String("openAllInBackground"))
	{
		m_ui->popupsValueLabel->setText(tr("Always (open in backgound)"));
	}
	else if (popupsPolicy == QLatin1String("blockAll"))
	{
		m_ui->popupsValueLabel->setText(tr("Never"));
	}
	else
	{
		m_ui->popupsValueLabel->setText(tr("Ask"));
	}

	if (m_sslInformation.certificates.isEmpty())
	{
		m_ui->tabWidget->setTabEnabled(2, false);
	}
	else
	{
		const QSslCertificate certificate(m_sslInformation.certificates.first());

		m_ui->certificateIssuedToLabelWidget->setText(certificate.subjectInfo(QSslCertificate::CommonName).join(QLatin1String(", ")));
		m_ui->certificateIssuedByLabelWidget->setText(certificate.issuerInfo(QSslCertificate::CommonName).join(QLatin1String(", ")));
		m_ui->certificateIssuedOnLabelWidget->setText(Utils::formatDateTime(certificate.effectiveDate()));
		m_ui->certificateExpiresOnLabelWidget->setText(Utils::formatDateTime(certificate.expiryDate()));
		m_ui->cipherProtocolLabelWidget->setText(m_sslInformation.cipher.protocolString());
		m_ui->cipherAuthenticationMethodLabelWidget->setText(m_sslInformation.cipher.authenticationMethod());
		m_ui->cipherEncryptionMethodLabelWidget->setText(m_sslInformation.cipher.encryptionMethod());
		m_ui->cipherKeyExchangeMethodLabelWidget->setText(m_sslInformation.cipher.keyExchangeMethod());
	}

	if (m_sslInformation.errors.isEmpty())
	{
		m_ui->sslErrorsHeaderLabel->hide();
		m_ui->sslErrorsViewWidget->hide();
	}
	else
	{
		QStandardItemModel *sslErrorsModel(new QStandardItemModel(this));
		sslErrorsModel->setHorizontalHeaderLabels(QStringList({tr("Error Message"), tr("URL")}));

		for (int i = 0; i < m_sslInformation.errors.count(); ++i)
		{
			QList<QStandardItem*> items({new QStandardItem(m_sslInformation.errors.at(i).second.errorString()), new QStandardItem(m_sslInformation.errors.at(i).first.toDisplayString())});
			items[0]->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
			items[0]->setToolTip(items[0]->text());
			items[1]->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
			items[1]->setToolTip(items[1]->text());

			sslErrorsModel->appendRow(items);
		}

		m_ui->sslErrorsViewWidget->setModel(sslErrorsModel);
	}

	setWindowTitle(tr("Information for %1").arg(host));

	connect(m_ui->preferencesDetailsButton, SIGNAL(clicked(bool)), this, SLOT(showPreferences()));
	connect(m_ui->certificateDetailsButton, SIGNAL(clicked(bool)), this, SLOT(showCertificate()));
}
Exemple #24
0
// necessary indication only, not sufficient for primary validation!
static bool isSelfSigned(const QSslCertificate &certificate)
{
    return certificate.issuerInfo(QSslCertificate::CommonName) == certificate.subjectInfo(QSslCertificate::CommonName) &&
           certificate.issuerInfo(QSslCertificate::OrganizationalUnitName) == certificate.subjectInfo(QSslCertificate::OrganizationalUnitName);
}
Exemple #25
0
void NetworkManager::sslError(QNetworkReply* reply, QList<QSslError> errors)
{
    if (m_ignoreAllWarnings || reply->property("downReply").toBool()) {
        reply->ignoreSslErrors(errors);
        return;
    }

    QNetworkRequest request = reply->request();
    QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100));
    WebPage* webPage = static_cast<WebPage*>(v.value<void*>());
    if (!WebPage::isPointerSafeToUse(webPage)) {
        return;
    }

    QHash<QSslCertificate, QStringList> errorHash;
    foreach (const QSslError &error, errors) {
        // Weird behavior on Windows
        if (error.error() == QSslError::NoError) {
            continue;
        }

        const QSslCertificate cert = error.certificate();

        if (errorHash.contains(cert)) {
            errorHash[cert].append(error.errorString());
        }
        else {
            errorHash.insert(cert, QStringList(error.errorString()));
        }
    }

    // User already rejected those certs on this page
    if (webPage->containsRejectedCerts(errorHash.keys())) {
        return;
    }

    QString title = tr("SSL Certificate Error!");
    QString text1 = tr("The page you are trying to access has the following errors in the SSL certificate:");

    QString certs;

    QHash<QSslCertificate, QStringList>::const_iterator i = errorHash.constBegin();
    while (i != errorHash.constEnd()) {
        const QSslCertificate cert = i.key();
        const QStringList errors = i.value();

        if (m_localCerts.contains(cert) || m_tempAllowedCerts.contains(cert) || errors.isEmpty()) {
            ++i;
            continue;
        }

        certs += "<ul><li>";
        certs += tr("<b>Organization: </b>") + CertificateInfoWidget::clearCertSpecialSymbols(cert.subjectInfo(QSslCertificate::Organization));
        certs += "</li><li>";
        certs += tr("<b>Domain Name: </b>") + CertificateInfoWidget::clearCertSpecialSymbols(cert.subjectInfo(QSslCertificate::CommonName));
        certs += "</li><li>";
        certs += tr("<b>Expiration Date: </b>") + cert.expiryDate().toString("hh:mm:ss dddd d. MMMM yyyy");
        certs += "</li></ul>";

        certs += "<ul>";
        foreach (const QString &error, errors) {
            certs += "<li>";
            certs += tr("<b>Error: </b>") + error;
            certs += "</li>";
        }
        certs += "</ul>";

        ++i;
    }
static void ReportInvalidCertificate(const QSslCertificate& cert)
{
    // ToDo: These messages get tiresome in the debug.log's  For now disabling them, but should turn them on
#if CLIENT_VERSION_IS_RELEASE == true
    qDebug() << "ReportInvalidCertificate : Payment server found an invalid certificate: " << cert.subjectInfo(QSslCertificate::CommonName);
#endif
}
Exemple #27
0
void CertificateDialog::updateValue()
{
	const QSslCertificate certificate(m_certificates.value(m_ui->chainItemView->currentIndex().data(Qt::UserRole).toInt()));
	const CertificateField field(static_cast<CertificateField>(m_ui->detailsItemView->currentIndex().data(Qt::UserRole).toInt()));

	m_ui->valueTextEdit->clear();

	switch (field)
	{
		case ValidityField:
		case PublicKeyField:
		case ExtensionsField:
		case DigestField:
			break;
		case VersionField:
			m_ui->valueTextEdit->setPlainText(QString(certificate.version()));

			break;
		case SerialNumberField:
			m_ui->valueTextEdit->setPlainText(formatHex(QString(certificate.serialNumber()), QLatin1Char(':')));

			break;
		case SignatureAlgorithmField:
			m_ui->valueTextEdit->setPlainText(QRegularExpression(QLatin1String("Signature Algorithm:(.+)")).match(certificate.toText()).captured(1).trimmed());

			break;
		case IssuerField:
			{
				const QList<QByteArray> attributes(certificate.issuerInfoAttributes());

				for (int i = 0; i < attributes.count(); ++i)
				{
					m_ui->valueTextEdit->appendPlainText(QStringLiteral("%1 = %2").arg(QString(attributes.at(i))).arg(certificate.issuerInfo(attributes.at(i)).join(QLatin1String(", "))));
				}
			}

			break;
		case ValidityNotBeforeField:
			m_ui->valueTextEdit->setPlainText(certificate.effectiveDate().toString(QLatin1String("yyyy-MM-dd hh:mm:ss t")));

			break;
		case ValidityNotAfterField:
			m_ui->valueTextEdit->setPlainText(certificate.expiryDate().toString(QLatin1String("yyyy-MM-dd hh:mm:ss t")));

			break;
		case SubjectField:
			{
				const QList<QByteArray> attributes(certificate.subjectInfoAttributes());

				for (int i = 0; i < attributes.count(); ++i)
				{
					m_ui->valueTextEdit->appendPlainText(QStringLiteral("%1 = %2").arg(QString(attributes.at(i))).arg(certificate.subjectInfo(attributes.at(i)).join(QLatin1String(", "))));
				}
			}

			break;
		case PublicKeyValueField:
			{
				const QRegularExpression expression(QLatin1String("Public-Key:[.\\s\\S]+Modulus:([.\\s\\S]+)Exponent:(.+)"), QRegularExpression::MultilineOption);
				const QRegularExpressionMatch match(expression.match(certificate.toText()));

				if (match.hasMatch())
				{
					m_ui->valueTextEdit->setPlainText(tr("Modulus:\n%1\n\nExponent: %2").arg(formatHex(match.captured(1).trimmed().mid(3))).arg(match.captured(2).trimmed()));
				}
			}

			break;
		case PublicKeyAlgorithmField:
			m_ui->valueTextEdit->setPlainText(QRegularExpression(QLatin1String("Public Key Algorithm:(.+)")).match(certificate.toText()).captured(1).trimmed());

			break;
		case ExtensionField:
			{
				const QSslCertificateExtension extension(certificate.extensions().value(m_ui->detailsItemView->currentIndex().data(Qt::UserRole + 1).toInt()));

				m_ui->valueTextEdit->setPlainText(extension.isCritical() ? tr("Critical") : tr("Not Critical"));
				m_ui->valueTextEdit->appendPlainText(tr("OID: %1").arg(extension.oid()));

				if (!extension.value().isNull())
				{
					m_ui->valueTextEdit->appendPlainText(tr("Value:"));

					if (extension.value().type() == QVariant::List)
					{
						const QVariantList list(extension.value().toList());

						for (int i = 0; i < list.count(); ++i)
						{
							m_ui->valueTextEdit->appendPlainText(list.at(i).toString());
						}
					}
					else if (extension.value().type() == QVariant::Map)
					{
						const QVariantMap map(extension.value().toMap());
						QVariantMap::const_iterator iterator;

						for (iterator = map.constBegin(); iterator != map.constEnd(); ++iterator)
						{
							m_ui->valueTextEdit->appendPlainText(QStringLiteral("%1 = %2").arg(iterator.key()).arg(iterator.value().toString()));
						}
					}
					else
					{
						m_ui->valueTextEdit->appendPlainText(extension.value().toString());
					}
				}
			}

			break;
		case DigestSha1Field:
			m_ui->valueTextEdit->setPlainText(formatHex(QString(certificate.digest(QCryptographicHash::Sha1).toHex())));

			break;
		case DigestSha256Field:
			m_ui->valueTextEdit->setPlainText(formatHex(QString(certificate.digest(QCryptographicHash::Sha256).toHex())));

			break;
		default:
			break;
	}

	QTextCursor cursor(m_ui->valueTextEdit->textCursor());
	cursor.setPosition(0);

	m_ui->valueTextEdit->setTextCursor(cursor);
}
void NetworkManager::sslError(QNetworkReply* reply, QList<QSslError> errors)
{
    if (m_ignoreAllWarnings) {
        reply->ignoreSslErrors(errors);
        return;
    }

    if (reply->property("downReply").toBool()) {
        return;
    }

    int errorsIgnored = 0;
    foreach(const QSslError & error, errors) {
        if (m_ignoredCerts.contains(error.certificate())) {
            ++errorsIgnored;
        }
    }

    if (errorsIgnored == errors.count()) {
        return;
    }

    QNetworkRequest request = reply->request();
    QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100));
    WebPage* webPage = static_cast<WebPage*>(v.value<void*>());
    if (!webPage) {
        return;
    }

    QString title = tr("SSL Certificate Error!");
    QString text1 = tr("The page you are trying to access has the following errors in the SSL certificate:");

    QString certs;

    foreach(const QSslError & error, errors) {
        if (m_localCerts.contains(error.certificate())) {
            continue;
        }
        if (error.error() == QSslError::NoError) { //Weird behavior on Windows
            continue;
        }

        QSslCertificate cert = error.certificate();
        certs.append("<ul><li>");
        certs.append(tr("<b>Organization: </b>") + CertificateInfoWidget::clearCertSpecialSymbols(cert.subjectInfo(QSslCertificate::Organization)));
        certs.append("</li><li>");
        certs.append(tr("<b>Domain Name: </b>") + CertificateInfoWidget::clearCertSpecialSymbols(cert.subjectInfo(QSslCertificate::CommonName)));
        certs.append("</li><li>");
        certs.append(tr("<b>Expiration Date: </b>") + cert.expiryDate().toString("hh:mm:ss dddd d. MMMM yyyy"));
        certs.append("</li><li>");
        certs.append(tr("<b>Error: </b>") + error.errorString());
        certs.append("</li></ul>");
    }

    QString text2 = tr("Would you like to make an exception for this certificate?");
    QString message = QString("<b>%1</b><p>%2</p>%3<p>%4</p>").arg(title, text1, certs, text2);

    if (!certs.isEmpty())  {
        if (QMessageBox::critical(webPage->view(), tr("SSL Certificate Error!"), message,
                                  QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No) {
            return;
        }

        foreach(const QSslError & error, errors) {
            if (!m_localCerts.contains(error.certificate())) {
                addLocalCertificate(error.certificate());
            }
        }
    }

    reply->ignoreSslErrors(errors);
}
Exemple #29
0
static void ReportInvalidCertificate(const QSslCertificate& cert)
{
    qDebug() << "ReportInvalidCertificate : Payment server found an invalid certificate: " << cert.subjectInfo(QSslCertificate::CommonName);
}
QString SslCertificateMonitor::evaluateCertificateChange( const QString &peerName,
                                                          const QSslCertificate &cached,
                                                          const QSslCertificate &actual,
                                                          bool trusted )
{
    // BEWARE: check if the past cert had ssl errors or someone can just spoof
    // this stuff trivially. The info on the current cert is only trust-worthy if
    // trusted is true.

    bool cachedCertIsExpired = (cached.expiryDate() < QDateTime::currentDateTime());

    bool issuerIsSame = false;
    if ( cached.issuerInfo(QSslCertificate::Organization) == actual.issuerInfo(QSslCertificate::Organization)
         && cached.issuerInfo(QSslCertificate::CommonName) == actual.issuerInfo(QSslCertificate::CommonName)
         && cached.issuerInfo(QSslCertificate::LocalityName) == actual.issuerInfo(QSslCertificate::LocalityName)
         && cached.issuerInfo(QSslCertificate::OrganizationalUnitName) == actual.issuerInfo(QSslCertificate::OrganizationalUnitName)
         && cached.issuerInfo(QSslCertificate::CountryName) == actual.issuerInfo(QSslCertificate::CountryName)
         && cached.issuerInfo(QSslCertificate::StateOrProvinceName) == actual.issuerInfo(QSslCertificate::StateOrProvinceName) )
        {
            issuerIsSame = true;
        }

    bool cachedWasSelfSigned = false;
    if ( cached.issuerInfo(QSslCertificate::Organization) == cached.subjectInfo(QSslCertificate::Organization)
         && cached.issuerInfo(QSslCertificate::CommonName) == cached.subjectInfo(QSslCertificate::CommonName)
         && cached.issuerInfo(QSslCertificate::LocalityName) == cached.subjectInfo(QSslCertificate::LocalityName)
         && cached.issuerInfo(QSslCertificate::OrganizationalUnitName) == cached.subjectInfo(QSslCertificate::OrganizationalUnitName)
         && cached.issuerInfo(QSslCertificate::CountryName) == cached.subjectInfo(QSslCertificate::CountryName)
         && cached.issuerInfo(QSslCertificate::StateOrProvinceName) == cached.subjectInfo(QSslCertificate::StateOrProvinceName) )
        {
            cachedWasSelfSigned = true;
        }

    bool actualIsSelfSigned = false;
    if ( actual.issuerInfo(QSslCertificate::Organization) == actual.subjectInfo(QSslCertificate::Organization)
         && actual.issuerInfo(QSslCertificate::CommonName) == actual.subjectInfo(QSslCertificate::CommonName)
         && actual.issuerInfo(QSslCertificate::LocalityName) == actual.subjectInfo(QSslCertificate::LocalityName)
         && actual.issuerInfo(QSslCertificate::OrganizationalUnitName) == actual.subjectInfo(QSslCertificate::OrganizationalUnitName)
         && actual.issuerInfo(QSslCertificate::CountryName) == actual.subjectInfo(QSslCertificate::CountryName)
         && actual.issuerInfo(QSslCertificate::StateOrProvinceName) == actual.subjectInfo(QSslCertificate::StateOrProvinceName) )
        {
            actualIsSelfSigned = true;
        }

    /**
     * We have the following metrics with which to evaluate the certificate:
     * cachedCertIsExpired
     * issuerIsSame
     * cachedWasSelfSigned
     * actualIsSelfSigned
     * trusted
     *
     * Note that just because the certs are not self-signed doesn't mean the
     * CA that signed them is trusted, ideally we would be able to verify the
     * chain directly from the cert but the API does not allow this. For now,
     * we check if the current cert had any SSL errors by passing it in via
     * the 'trusted' variable.
     */

    if ( cachedCertIsExpired && issuerIsSame && trusted ) {
        QString message = tr("This is probably fine, but the certificate for %1 has changed " \
                             "since you previously visited. The old certificate has now " \
                             "expired and the new one is valid and from the same issuer.");

        message = message.arg(peerName);
        return message;
    }
    else if ( cachedCertIsExpired && trusted ) {
        // issuerIsSame == false
        QString message = tr("This is probably fine, but the certificate for %1 has changed " \
                             "since you previously visited. The old certificate has now " \
                             "expired and the new one is valid. T new certificate is from " \
                             "a different issuer however.");

        message = message.arg(peerName);
        return message;
    }
    else if ( !cachedCertIsExpired && issuerIsSame && trusted ) {
        QString message = tr("This is a bit suspicious, the certificate for %1 has changed " \
                             "since you previously visited, even though the old certificate " \
                             "would still be fine. The new one is valid and from the same "
                             "issuer.");

        message = message.arg(peerName);
        return message;

    }
    else if ( !cachedCertIsExpired && !issuerIsSame && cachedWasSelfSigned && trusted ) {
        QString message = tr("This is probably a good thing, but the certificate for %1 " \
                             "has changed since you previously visited. The old certificate " \
                             "was self-signed, and the new one has been issued by a trusted " \
                             "authority.");

        message = message.arg(peerName);
        return message;

    }
    else if ( !cachedCertIsExpired && !issuerIsSame && cachedWasSelfSigned && actualIsSelfSigned ) {
        QString message = tr("This is suspicious, the certificate for %1 has changed since you " \
                             "previously visited. The old certificate was self-signed and has not " \
                             "expired yet, the new one is self-signed as well, so we can't verify it.");

        message = message.arg(peerName);
        return message;
    }
    else if ( !cachedCertIsExpired && !issuerIsSame && !cachedWasSelfSigned && actualIsSelfSigned ) {
        QString message = tr("This is highly suspicious, you should not trust this site at the moment. " \
                             "The certificate for %1 has changed since you previously visited, the old " \
                             "certificate was not self-signed and has not expired yet, but the new one " \
                             "is self-signed.");

        message = message.arg(peerName);
        return message;
    }

}