示例#1
0
void NetworkManager::addLocalCertificate(const QSslCertificate &cert)
{
//    if (!cert.isValid()) {
//        return;
//    }

    m_localCerts.append(cert);
    QSslSocket::addDefaultCaCertificate(cert);

    QDir dir(mApp->getActiveProfilPath());
    if (!dir.exists("certificates")) {
        dir.mkdir("certificates");
    }

    QString certFileName = fileNameForCert(cert);
    QString fileName = qz_ensureUniqueFilename(mApp->getActiveProfilPath() + "certificates/" + certFileName);

    QFile file(fileName);
    if (file.open(QFile::WriteOnly)) {
        file.write(cert.toPem());
        file.close();
    }
    else {
        qWarning() << "NetworkManager::addLocalCertificate cannot write to file: " << fileName;
    }
}
void CertIdentity::setSslCert(const QSslCertificate &cert)
{
    if (cert.toPem() == _sslCert.toPem())
        return;
    _sslCert = cert;
    _isDirty = true;
}
示例#3
0
void SslCertificateManager::askForCertificateAcceptance(
    const QString &hostName, const QSslCertificate &certificate, const QList<QSslError> &errors,
    const std::function<void()> &onAccepted, const std::function<void()> &onRejected)
{
    auto hostCertificate = SslCertificate{hostName, certificate.toPem().toHex()};
    auto sslCertificateErrorDialog = new SslCertificateErrorDialog{hostCertificate, errors};
    sslCertificateErrorDialog->setSslCertificateRepository(m_sslCertificateRepository);
    connect(sslCertificateErrorDialog, &SslCertificateErrorDialog::accepted, onAccepted);
    connect(sslCertificateErrorDialog, &SslCertificateErrorDialog::rejected, onRejected);

    sslCertificateErrorDialog->show();
}
void SslCertificateMonitor::addCertificate(const QString &peerName, const QSslCertificate &cert)
{
    if (!hasCertificateCache()) {
        bool ok = createCertificateCache();
        if (!ok)
            return;
    }

    QString cacheEntry = d->cacheDir + QLatin1Char('/') + peerName;
    QFile f( cacheEntry );
    if (!f.open(QIODevice::WriteOnly))
        return;

    // TODO: write the whole chain
    f.write(cert.toPem());
    f.close();
}
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());
}
示例#6
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();
	}
}
示例#7
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;
}
示例#8
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;
        }
    }
示例#9
0
bool SslCertificateManager::acceptCertificate(const QString &hostName, const QSslCertificate &certificate) const
{
	auto hostCertificate = SslCertificate{hostName, certificate.toPem().toHex()};
	return m_sslCertificateRepository->containsCertificate(hostCertificate);
}
示例#10
0
inline uint qHash(const QSslCertificate &cert)
{
    return qHash(cert.toPem());
}
示例#11
0
void
PlaydarApi::start()
{
    Q_D( PlaydarApi );
    if ( !d->session.isNull() )
    {
        tLog() << "HTTPd session already exists, returning";
        return;
    }

    d->session.reset( new QxtHttpSessionManager() );
    d->connector.reset( new QxtHttpServerConnector() );
    d->tlsSession.reset( new QxtHttpSessionManager() );
    d->tlsConnector.reset( new QxtHttpsServerConnector() );
    if ( d->session.isNull() || d->connector.isNull()
         || d->tlsSession.isNull() || d->tlsConnector.isNull() )
    {
        if ( !d->session.isNull() )
            d->session.reset();
        if ( !d->connector.isNull() )
            d->connector.reset();
        if ( !d->tlsSession.isNull() )
            d->tlsSession.reset();
        if ( !d->tlsConnector.isNull() )
            d->tlsConnector.reset();
        tLog() << "Failed to start HTTPd, could not create object";
        return;
    }

    d->session->setListenInterface( d->ha );
    d->session->setPort( d->port );
    d->session->setConnector( d->connector.data() );

    d->instance.reset( new Api_v1( d->session.data() ) );
    d->session->setStaticContentService( d->instance.data() );

    tLog() << "Starting HTTPd on" << d->session->listenInterface().toString() << d->session->port();
    d->session->start();

    d->tlsSession->setListenInterface( d->ha );
    d->tlsSession->setPort( d->sport );
    d->tlsSession->setConnector( d->tlsConnector.data() );

    d->tlsInstance.reset( new Api_v1( d->tlsSession.data() ) );
    d->tlsSession->setStaticContentService( d->tlsInstance.data() );

    QByteArray settingsKey = TomahawkSettings::instance()->playdarKey();
    QSslKey key;
    if ( settingsKey.isNull() || settingsKey.isEmpty() )
    {
        // Generate a SSL key
        key = KeyBuilder::generate( QSsl::Rsa, KeyBuilder::StrengthNormal );
        TomahawkSettings::instance()->setPlaydarKey( key.toPem() );
    }
    else
    {
        // Restore key
        key = QSslKey( settingsKey, QSsl::Rsa );
    }

    QByteArray settingsCert = TomahawkSettings::instance()->playdarCertificate();
    QSslCertificate cert;
    if ( settingsCert.isNull() || settingsCert.isEmpty() )
    {
        // Generate a SSL certificate
        CertificateRequestBuilder reqbuilder;
        reqbuilder.setVersion( 1 );
        reqbuilder.setKey( key );
        reqbuilder.addNameEntry( Certificate::EntryCountryName, "GB" );
        reqbuilder.addNameEntry( Certificate::EntryOrganizationName, "Tomahawk Player (Desktop)" );
        reqbuilder.addNameEntry( Certificate::EntryCommonName, "localhost" );

        // Sign the request
        CertificateRequest req = reqbuilder.signedRequest(key);

        // Now make a certificate
        CertificateBuilder builder;
        builder.setRequest( req );

        builder.setVersion( 3 );
        builder.setSerial( uuid().toLatin1() );
        builder.setActivationTime( QDateTime::currentDateTimeUtc());
        builder.setExpirationTime( QDateTime::currentDateTimeUtc().addYears( 10 ) );
        builder.setBasicConstraints( false );
        builder.addKeyPurpose( CertificateBuilder::PurposeWebServer );
        builder.setKeyUsage( CertificateBuilder::UsageKeyAgreement|CertificateBuilder::UsageKeyEncipherment );
        builder.addSubjectKeyIdentifier();

        cert = builder.signedCertificate( key );
        TomahawkSettings::instance()->setPlaydarCertificate( cert.toPem() );
    }
    else
    {
        cert = QSslCertificate( settingsCert );
    }

    QxtSslServer* sslServer = d->tlsConnector->tcpServer();
    sslServer->setPrivateKey( key );
    sslServer->setLocalCertificate( cert );

    tLog() << "Starting HTTPSd on" << d->tlsSession->listenInterface().toString() << d->tlsSession->port();
    tLog() << Q_FUNC_INFO << d->tlsSession->start();
}
示例#12
0
void DataPlaneServer::start() {
    server_addr.s6.sin6_family = AF_INET6;
    // we listen on public IP, which is the one stored in the DB.
    struct in6_addr servIp;
    inet_pton(AF_INET6, qSql->getLocalIP().toUtf8().data(), &servIp);
    server_addr.s6.sin6_addr = servIp; //in6addr_any;
    server_addr.s6.sin6_port = htons(DATAPLANEPORT);

    const int on = 1, off = 0;

    OpenSSL_add_ssl_algorithms();

    SSL_load_error_strings();
    ctx = SSL_CTX_new(DTLSv1_server_method());

    SSL_CTX_set_cipher_list(ctx, DTLS_ENCRYPT);
    SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);

    // get certificate and key from SQL & use them
    ConnectionInitiator* i = ConnectionInitiator::getInstance();
    QSslCertificate cert = i->getLocalCertificate();
    QByteArray certBytesPEM = cert.toPem();
    char* x509buffer = certBytesPEM.data();

    BIO *bi;
    bi = BIO_new_mem_buf(x509buffer, certBytesPEM.length());
    X509 *x;
    x = PEM_read_bio_X509(bi, NULL, NULL, NULL);

    if (!SSL_CTX_use_certificate(ctx,x)) {
        qWarning() << "ERROR: no certificate found!";
        UnixSignalHandler::termSignalHandler(0);
    }

    if (x != NULL) X509_free(x);
    if (bi != NULL) BIO_free(bi);

    QSslKey key = i->getPrivateKey();
    QByteArray keyBytesPEM = key.toPem();
    char* keyBuffer = keyBytesPEM.data();

    bi = BIO_new_mem_buf(keyBuffer, keyBytesPEM.length());
    EVP_PKEY *pkey;
    pkey = PEM_read_bio_PrivateKey(bi, NULL, NULL, NULL);

    if (!SSL_CTX_use_PrivateKey(ctx, pkey)) {
        qWarning() << "ERROR: no private key found!";
        UnixSignalHandler::termSignalHandler(0);
    }

    if (pkey != NULL) EVP_PKEY_free(pkey);
    if (bi != NULL) BIO_free(bi);

    if (!SSL_CTX_check_private_key (ctx)) {
        qWarning() << "ERROR: invalid private key!";
        UnixSignalHandler::termSignalHandler(0);
    }
    /* Client has to authenticate */
    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, dtls_verify_callback);

    SSL_CTX_set_read_ahead(ctx, 1);
    SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie);
    SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie);

    fd = socket(server_addr.ss.ss_family, SOCK_DGRAM, 0);
    if (fd < 0) {
        qWarning() << "Could not open SOCK_DGRAM";
        UnixSignalHandler::termSignalHandler(0);
    }

#ifdef WIN32
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*) &on, (socklen_t) sizeof(on));
#else
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void*) &on, (socklen_t) sizeof(on));
#ifdef SO_REUSEPORT
    setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (const void*) &on, (socklen_t) sizeof(on));
#endif
#endif

    setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&off, sizeof(off));
    bind(fd, (const struct sockaddr *) &server_addr, sizeof(struct sockaddr_in6));

    notif = new QSocketNotifier(fd, QSocketNotifier::Read);
    connect(notif, SIGNAL(activated(int)), this, SLOT(readyRead(int)));
}