示例#1
0
QSslCertificate QPKCS11Private::readCert( CK_SLOT_ID slot )
{
	if( session )
		f->C_CloseSession( session );
	session = 0;
	err = f->C_OpenSession( slot, CKF_SERIAL_SESSION, 0, 0, &session );
	if( err != CKR_OK )
		return QSslCertificate();

	CK_OBJECT_HANDLE obj = CK_INVALID_HANDLE;
	if( !findObject( CKO_CERTIFICATE, &obj ) || obj == CK_INVALID_HANDLE )
		return QSslCertificate();

	unsigned long size = 0;
	if( !attribute( obj, CKA_VALUE, 0, size ) )
		return QSslCertificate();

	char *cert_data = new char[size];
	if( !attribute( obj, CKA_VALUE, (unsigned char*)cert_data, size ) )
	{
		delete [] cert_data;
		return QSslCertificate();
	}

	QSslCertificate cert = QSslCertificate( QByteArray( cert_data, size ), QSsl::Der );
	delete [] cert_data;
	return cert;
}
示例#2
0
QSslCertificate AccessCert::cert()
{
#ifdef Q_OS_MAC
	SecIdentityRef identity = 0;
	OSStatus err = SecIdentityCopyPreference( CFSTR("ocsp.sk.ee"), 0, 0, &identity );
	if( !identity )
		return QSslCertificate();

	SecCertificateRef certref = 0;
	err = SecIdentityCopyCertificate( identity, &certref );
	CFRelease( identity );
	if( !certref )
		return QSslCertificate();

	CFDataRef certdata = SecCertificateCopyData( certref );
	CFRelease( certref );
	if( !certdata )
		return QSslCertificate();

	QSslCertificate cert(
		QByteArray( (const char*)CFDataGetBytePtr( certdata ), CFDataGetLength( certdata ) ), QSsl::Der );
	CFRelease( certdata );
	return cert;
#else
	return PKCS12Certificate::fromPath(
		Application::confValue( Application::PKCS12Cert ).toString(),
		Application::confValue( Application::PKCS12Pass ).toString() ).certificate();
#endif
}
/*!
  Creates a self-signed certificate by signing the certificate with the specified
  key.
 */
QSslCertificate CertificateBuilder::signedCertificate(const QSslKey &qkey)
{
    gnutls_x509_privkey_t key = qsslkey_to_key(qkey, &d->errnumber);
    if (GNUTLS_E_SUCCESS != d->errnumber) {
        gnutls_x509_privkey_deinit(key);
        return QSslCertificate();
    };

    gnutls_privkey_t abstractKey;
    d->errnumber = gnutls_privkey_init(&abstractKey);
    if (GNUTLS_E_SUCCESS != d->errnumber) {
        gnutls_x509_privkey_deinit(key);
        return QSslCertificate();
    }

    gnutls_privkey_import_x509(abstractKey, key, GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE);

    d->errnumber = gnutls_x509_crt_privkey_sign(d->crt, d->crt, abstractKey, GNUTLS_DIG_SHA1, 0);

    gnutls_x509_privkey_deinit(key);

    if (GNUTLS_E_SUCCESS != d->errnumber)
        return QSslCertificate();

    return crt_to_qsslcert(d->crt, &d->errnumber);    
}
示例#4
0
void KeyAddDialog::addFile()
{
	QString file = QFileDialog::getOpenFileName( this, windowTitle(),
		QDesktopServices::storageLocation( QDesktopServices::DocumentsLocation ),
		tr("Certificates (*.pem *.cer *.crt)") );
	if( file.isEmpty() )
		return;

	QFile f( file );
	if( !f.open( QIODevice::ReadOnly ) )
	{
		QMessageBox::warning( this, windowTitle(), tr("Failed to open certifiacte") );
		return;
	}

	CKey k( QSslCertificate( &f, QSsl::Pem ) );
	if( k.cert.isNull() )
	{
		f.reset();
		k.setCert( QSslCertificate( &f, QSsl::Der ) );
	}
	if( k.cert.isNull() )
	{
		QMessageBox::warning( this, windowTitle(), tr("Failed to read certificate") );
	}
	else if( !SslCertificate( k.cert ).keyUsage().contains( SslCertificate::DataEncipherment ) )
	{
		QMessageBox::warning( this, windowTitle(), tr("This certificate is not usable for crypting") );
	}
	else
		addKeys( QList<CKey>() << k );

	f.close();
}
示例#5
0
文件: Cert.cpp 项目: CarlsonER/mumble
Settings::KeyPair CertWizard::importCert(QByteArray data, const QString &pw) {
	X509 *x509 = NULL;
	EVP_PKEY *pkey = NULL;
	PKCS12 *pkcs = NULL;
	BIO *mem = NULL;
	STACK_OF(X509) *certs = NULL;
	Settings::KeyPair kp;
	int ret = 0;

	mem = BIO_new_mem_buf(data.data(), data.size());
	Q_UNUSED(BIO_set_close(mem, BIO_NOCLOSE));
	pkcs = d2i_PKCS12_bio(mem, NULL);
	if (pkcs) {
		ret = PKCS12_parse(pkcs, NULL, &pkey, &x509, &certs);
		if (pkcs && !pkey && !x509 && ! pw.isEmpty()) {
			if (certs) {
				if (ret)
					sk_X509_free(certs);
				certs = NULL;
			}
			ret = PKCS12_parse(pkcs, pw.toUtf8().constData(), &pkey, &x509, &certs);
		}
		if (pkey && x509 && X509_check_private_key(x509, pkey)) {
			unsigned char *dptr;
			QByteArray key, crt;

			key.resize(i2d_PrivateKey(pkey, NULL));
			dptr=reinterpret_cast<unsigned char *>(key.data());
			i2d_PrivateKey(pkey, &dptr);

			crt.resize(i2d_X509(x509, NULL));
			dptr=reinterpret_cast<unsigned char *>(crt.data());
			i2d_X509(x509, &dptr);

			QSslCertificate qscCert = QSslCertificate(crt, QSsl::Der);
			QSslKey qskKey = QSslKey(key, QSsl::Rsa, QSsl::Der);

			QList<QSslCertificate> qlCerts;
			qlCerts << qscCert;

			if (certs) {
				for (int i=0;i<sk_X509_num(certs);++i) {
					X509 *c = sk_X509_value(certs, i);

					crt.resize(i2d_X509(c, NULL));
					dptr=reinterpret_cast<unsigned char *>(crt.data());
					i2d_X509(c, &dptr);

					QSslCertificate cert = QSslCertificate(crt, QSsl::Der);
					qlCerts << cert;
				}
			}
			bool valid = ! qskKey.isNull();
			foreach(const QSslCertificate &cert, qlCerts)
				valid = valid && ! cert.isNull();
			if (valid)
				kp = Settings::KeyPair(qlCerts, qskKey);
		}
	}
void QMyServer::_startServerEncryption ()
{
    if (QSslSocket::supportsSsl())
        qDebug()<< "Supporto SSL attivo....";
    else
        qDebug()<< "Supporto SSL non attivo.... Controlla l'include della libreria libssl .... ";

    QFile cert(":/files/resources/mycertcert.pem");
    if (!cert.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QByteArray certba = cert.readAll();

    QFile keyfile(":/files/resources/mycertkey.pem");
    if (!keyfile.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QByteArray keyba = keyfile.readAll();

    QSslKey keyKey(keyba, QSsl::Rsa);

    if (keyKey.isNull()) {
        qWarning("Key is null");
        socket->disconnectFromHost();
        return;
    }

    socket->setLocalCertificate( QSslCertificate( certba ) );
    socket->setPrivateKey(keyKey);
    socket->startServerEncryption();

}
void IdentityEditWidget::saveToIdentity(CertIdentity *id)
{
    QRegExp linebreaks = QRegExp("[\\r\\n]");
    id->setRealName(ui.realName->text());
    QStringList nicks;
    for (int i = 0; i < ui.nicknameList->count(); i++) {
        nicks << ui.nicknameList->item(i)->text();
    }
    id->setNicks(nicks);
    id->setAwayNick(ui.awayNick->text());
    id->setAwayNickEnabled(true);
    id->setAwayReason(ui.awayReason->text().remove(linebreaks));
    id->setAwayReasonEnabled(true);
    id->setAutoAwayEnabled(ui.autoAwayEnabled->isChecked());
    id->setAutoAwayTime(ui.autoAwayTime->value());
    id->setAutoAwayReason(ui.autoAwayReason->text().remove(linebreaks));
    id->setAutoAwayReasonEnabled(ui.autoAwayReasonEnabled->isChecked());
    id->setDetachAwayEnabled(ui.detachAwayEnabled->isChecked());
    id->setDetachAwayReason(ui.detachAwayReason->text().remove(linebreaks));
    id->setDetachAwayReasonEnabled(true);
    id->setIdent(ui.ident->text());
    id->setKickReason(ui.kickReason->text().remove(linebreaks));
    id->setPartReason(ui.partReason->text().remove(linebreaks));
    id->setQuitReason(ui.quitReason->text().remove(linebreaks));
#ifdef HAVE_SSL
    id->setSslKey(QSslKey(ui.keyTypeLabel->property("sslKey").toByteArray(), (QSsl::KeyAlgorithm)(ui.keyTypeLabel->property("sslKeyType").toInt())));
    id->setSslCert(QSslCertificate(ui.certOrgLabel->property("sslCert").toByteArray()));
#endif
}
示例#8
0
SslServer::SslServer(const QString &certFile, const QString &keyFile, QObject *parent) :
	QTcpServer(parent)
{
	if(!QSslSocket::supportsSsl()) {
		logger::error() << "SSL support not available!";
		return;
	}

	QFile cert(certFile);
	if(!cert.open(QFile::ReadOnly)) {
		logger::error() << "Couldn't open certificate:" << cert.errorString();
		return;
	}

	QFile key(keyFile);
	if(!key.open(QFile::ReadOnly)) {
		logger::error() << "Couldn't open private key:" << key.errorString();
		return;
	}

	_cert = QSslCertificate(&cert);
	if(_cert.isNull())
		logger::error() << "Invalid certificate";

	_key = QSslKey(&key, QSsl::Rsa);
	if(_key.isNull())
		logger::error() << "Invalid private key";
}
示例#9
0
const QSslCertificate QgsAuthSslConfigWidget::sslCertificate()
{
  if ( mDisabled )
  {
    return QSslCertificate();
  }
  return mCert;
}
const QPair<QSslCertificate, QSslKey> QgsAuthImportIdentityDialog::certBundleToImport()
{
  if ( mDisabled )
  {
    return qMakePair( QSslCertificate(), QSslKey() );
  }
  return mCertBundle;
}
示例#11
0
QSslCertificate WebPage::sslCertificate()
{
    if (url().scheme() == QLatin1String("https") && QzTools::isCertificateValid(m_sslCert)) {
        return m_sslCert;
    }

    return QSslCertificate();
}
示例#12
0
QList<QSslCertificate> CertStore::list() const
{
	QList<QSslCertificate> list;
	PCCERT_CONTEXT c = 0;
	while( (c = CertEnumCertificatesInStore( d->s, c )) )
		list << QSslCertificate( QByteArray( (char*)c->pbCertEncoded, c->cbCertEncoded ), QSsl::Der );
	CertFreeCertificateContext( c );
	return list;
}
示例#13
0
QgsPkiBundle::QgsPkiBundle( const QSslCertificate &clientCert,
                            const QSslKey &clientKey,
                            const QList<QSslCertificate> &caChain )
    : mCert( QSslCertificate() )
    , mCertKey( QSslKey() )
    , mCaChain( caChain )
{
  setClientCert( clientCert );
  setClientKey( clientKey );
}
示例#14
0
QSslCertificate SafetPKCS12::fromX509( X509 * x509 )
{
    unsigned char *cert = NULL;
    int len = i2d_X509( (X509*)x509, &cert );
    QByteArray der;
    if( len >= 0 )
        der = QByteArray( (char*)cert, len );
    OPENSSL_free( cert );
    return QSslCertificate( der, QSsl::Der );
}
/*!
  Creates a certificate signed by the specified CA certificate using the
  CA key.
 */
QSslCertificate CertificateBuilder::signedCertificate(const QSslCertificate &qcacert, const QSslKey &qcakey)
{
    //
    // Extract the CA key
    //
    gnutls_x509_privkey_t key = qsslkey_to_key(qcakey, &d->errnumber);
    if (GNUTLS_E_SUCCESS != d->errnumber) {
        gnutls_x509_privkey_deinit(key);
        return QSslCertificate();
    };

    gnutls_privkey_t abstractKey;
    d->errnumber = gnutls_privkey_init(&abstractKey);
    if (GNUTLS_E_SUCCESS != d->errnumber) {
        gnutls_x509_privkey_deinit(key);
        return QSslCertificate();
    }

    gnutls_privkey_import_x509(abstractKey, key, GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE);

    //
    // Extract the CA cert
    //
    gnutls_x509_crt_t cacrt = qsslcert_to_crt(qcacert, &d->errnumber);
    if (GNUTLS_E_SUCCESS != d->errnumber) {
        gnutls_x509_privkey_deinit(key);
        return QSslCertificate();
    }

    //
    // Sign the cert
    //
    d->errnumber = gnutls_x509_crt_privkey_sign(d->crt, cacrt, abstractKey, GNUTLS_DIG_SHA1, 0);

    gnutls_x509_crt_deinit(cacrt);
    gnutls_x509_privkey_deinit(key);

    if (GNUTLS_E_SUCCESS != d->errnumber)
        return QSslCertificate();

    return crt_to_qsslcert(d->crt, &d->errnumber);
}
示例#16
0
QgsAuthConfigSslServer::QgsAuthConfigSslServer()
  : mSslHostPort( QString() )
  , mSslCert( QSslCertificate() )
  , mSslIgnoredErrors( QList<QSslError::SslError>() )
{
  // TODO: figure out if Qt 5 has changed yet again, e.g. TLS-only
  mQtVersion = 480;
  // Qt 4.8 defaults to SecureProtocols, i.e. TlsV1SslV3
  // http://qt-project.org/doc/qt-4.8/qssl.html#SslProtocol-enum
  mSslProtocol = QSsl::SecureProtocols;
}
示例#17
0
QSslCertificate SslCertificateMonitor::cachedCertificate(const QString &peerName)
{
    QString cacheEntry = d->cacheDir + QLatin1Char('/') + peerName;
    QFile f( cacheEntry );
    if (!f.open(QIODevice::ReadOnly))
        return QSslCertificate();

    QSslCertificate cert(&f);
    f.close();
    
    return cert;
}
void QtCertificateViewerDialog::setCertificateChain(const std::vector<Certificate::ref>& chain) {
	// clean widgets
	ui->certChainTreeWidget->clear();

	if (chain.empty()) return;

	// convert Swift certificate chain to qt certificate chain (root goes first)
	currentChain.clear();
	foreach(Certificate::ref cert, chain) {
		ByteArray certAsDer = cert->toDER();
		QByteArray dataArray(reinterpret_cast<const char*>(certAsDer.data()), certAsDer.size());
		currentChain.push_front(QSslCertificate(dataArray, QSsl::Der));
	}
示例#19
0
/**
 * Set the label to indicate a lack of connection.
 * Context menu will be disabled.
 */
void NetStatus::hostDisconnected()
{
    _address = QString();
    _label->setText(tr("not connected"));

    _urlaction->setEnabled(false);
    _copyaction->setEnabled(false);
    _discoverIp->setVisible(false);

    message(tr("Disconnected"));
    _icon->hide();
    setSecurityLevel(net::Server::NO_SECURITY, QSslCertificate());
}
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;
}
示例#21
0
SslParams::SslParams( const QString & certFile, const QString & keyFile, QObject * parent )
            : QObject( parent )
{
      QFile fc( certFile, this );
      fc.open( QFile::ReadOnly );
      certificate = QSslCertificate( fc.readAll() );
      fc.close();

      ca << certificate;

      QFile fk( keyFile, this );
      fk.open( QFile::ReadOnly );
      privateKey = QSslKey( fk.readAll(), QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey);//, passwd );
      fk.close();
}
示例#22
0
文件: Cert.cpp 项目: CarlsonER/mumble
Settings::KeyPair CertWizard::generateNewCert(QString qsname, const QString &qsemail) {
	CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

	X509 *x509 = X509_new();
	EVP_PKEY *pkey = EVP_PKEY_new();
	RSA *rsa = RSA_generate_key(2048,RSA_F4,NULL,NULL);
	EVP_PKEY_assign_RSA(pkey, rsa);

	X509_set_version(x509, 2);
	ASN1_INTEGER_set(X509_get_serialNumber(x509),1);
	X509_gmtime_adj(X509_get_notBefore(x509),0);
	X509_gmtime_adj(X509_get_notAfter(x509),60*60*24*365*20);
	X509_set_pubkey(x509, pkey);

	X509_NAME *name=X509_get_subject_name(x509);

	if (qsname.isEmpty())
		qsname = tr("Mumble User");

	X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, reinterpret_cast<unsigned char *>(qsname.toUtf8().data()), -1, -1, 0);
	X509_set_issuer_name(x509, name);
	add_ext(x509, NID_basic_constraints, SSL_STRING("critical,CA:FALSE"));
	add_ext(x509, NID_ext_key_usage, SSL_STRING("clientAuth"));
	add_ext(x509, NID_subject_key_identifier, SSL_STRING("hash"));
	add_ext(x509, NID_netscape_comment, SSL_STRING("Generated by Mumble"));
	add_ext(x509, NID_subject_alt_name, QString::fromLatin1("email:%1").arg(qsemail).toUtf8().data());

	X509_sign(x509, pkey, EVP_sha1());

	QByteArray crt, key;

	crt.resize(i2d_X509(x509, NULL));
	unsigned char *dptr=reinterpret_cast<unsigned char *>(crt.data());
	i2d_X509(x509, &dptr);

	QSslCertificate qscCert = QSslCertificate(crt, QSsl::Der);

	key.resize(i2d_PrivateKey(pkey, NULL));
	dptr=reinterpret_cast<unsigned char *>(key.data());
	i2d_PrivateKey(pkey, &dptr);

	QSslKey qskKey = QSslKey(key, QSsl::Rsa, QSsl::Der);

	QList<QSslCertificate> qlCert;
	qlCert << qscCert;

	return Settings::KeyPair(qlCert, qskKey);
}
void QtWebKitNetworkManager::requestFinished(QNetworkReply *reply)
{
	if (reply)
	{
		if (reply == m_baseReply)
		{
			if (reply->sslConfiguration().isNull())
			{
				m_sslInformation.certificate = QSslCertificate();
				m_sslInformation.cipher = QSslCipher();
			}
			else
			{
				m_sslInformation.certificate = reply->sslConfiguration().peerCertificate();
				m_sslInformation.cipher = reply->sslConfiguration().sessionCipher();
			}
		}

		m_replies.remove(reply);
	}

	if (m_replies.isEmpty())
	{
		killTimer(m_updateTimer);

		m_dateDownloaded = QDateTime::currentDateTime();
		m_updateTimer = 0;

		updateStatus();

		if ((m_isSecure == 1 || (m_isSecure == 0 && m_contentState.testFlag(WindowsManager::SecureContentState))) && m_sslInformation.errors.isEmpty())
		{
			m_contentState = WindowsManager::SecureContentState;
		}

		emit contentStateChanged(m_contentState);
	}

	++m_finishedRequests;

	if (reply)
	{
		emit messageChanged(tr("Completed request to %1").arg(reply->url().host().isEmpty() ? QLatin1String("localhost") : reply->url().host()));

		disconnect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(downloadProgress(qint64,qint64)));
	}
}
示例#24
0
const QgsPkiBundle QgsPkiBundle::fromPkcs12Paths( const QString &bundlepath,
    const QString &bundlepass )
{
  QgsPkiBundle pkibundle;
  if ( QCA::isSupported( "pkcs12" )
       && !bundlepath.isEmpty()
       && ( bundlepath.endsWith( QLatin1String( ".p12" ), Qt::CaseInsensitive )
            || bundlepath.endsWith( QLatin1String( ".pfx" ), Qt::CaseInsensitive ) )
       && QFile::exists( bundlepath ) )
  {
    QCA::SecureArray passarray;
    if ( !bundlepass.isNull() )
      passarray = QCA::SecureArray( bundlepass.toUtf8() );
    QCA::ConvertResult res;
    QCA::KeyBundle bundle( QCA::KeyBundle::fromFile( bundlepath, passarray, &res, QStringLiteral( "qca-ossl" ) ) );
    if ( res == QCA::ConvertGood && !bundle.isNull() )
    {
      const QCA::CertificateChain cert_chain( bundle.certificateChain() );
      QSslCertificate cert( cert_chain.primary().toPEM().toLatin1() );
      if ( !cert.isNull() )
      {
        pkibundle.setClientCert( cert );
      }
      QSslKey cert_key( bundle.privateKey().toPEM().toLatin1(), QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey, QByteArray() );
      if ( !cert_key.isNull() )
      {
        pkibundle.setClientKey( cert_key );
      }

      if ( cert_chain.size() > 1 )
      {
        QList<QSslCertificate> ca_chain;
        for ( const auto &ca_cert : cert_chain )
        {
          if ( ca_cert != cert_chain.primary() )
          {
            ca_chain << QSslCertificate( ca_cert.toPEM().toLatin1() );
          }
        }
        pkibundle.setCaChain( ca_chain );
      }

    }
  }
  return pkibundle;
}
示例#25
0
void Servatrice::updateServerList()
{
	qDebug() << "Updating server list...";

	serverListMutex.lock();
	serverList.clear();

	QSqlQuery *query = servatriceDatabaseInterface->prepareQuery("select id, ssl_cert, hostname, address, game_port, control_port from {prefix}_servers order by id asc");
	servatriceDatabaseInterface->execSqlQuery(query);
	while (query->next()) {
		ServerProperties prop(query->value(0).toInt(), QSslCertificate(query->value(1).toString().toUtf8()), query->value(2).toString(), QHostAddress(query->value(3).toString()), query->value(4).toInt(), query->value(5).toInt());
		serverList.append(prop);
		qDebug() << QString("#%1 CERT=%2 NAME=%3 IP=%4:%5 CPORT=%6").arg(prop.id).arg(QString(prop.cert.digest().toHex())).arg(prop.hostname).arg(prop.address.toString()).arg(prop.gamePort).arg(prop.controlPort);
	}

	serverListMutex.unlock();
}
示例#26
0
void LdapSearch::timerEvent( QTimerEvent *e )
{
	LDAPMessage *result = 0;
	LDAP_TIMEVAL t = { 5, 0 };
	int err = ldap_result( d->ldap, d->msg_id, LDAP_MSG_ALL, &t, &result );
	switch( err )
	{
	case LDAP_SUCCESS: //Timeout
		return;
	case LDAP_RES_SEARCH_ENTRY:
	case LDAP_RES_SEARCH_RESULT:
		break;
	default:
		setLastError( tr("Failed to get result"), err );
		killTimer( e->timerId() );
		return;
	}
	killTimer( e->timerId() );

	QList<QSslCertificate> list;
	for( LDAPMessage *entry = ldap_first_entry( d->ldap, result );
		 entry; entry = ldap_next_entry( d->ldap, entry ) )
	{
		BerElement *pos = 0;
		for( char *attr = ldap_first_attribute( d->ldap, entry, &pos );
			 attr; attr = ldap_next_attribute( d->ldap, entry, pos ) )
		{
			if( qstrcmp( attr, "userCertificate;binary" ) == 0 )
			{
				berval **cert = ldap_get_values_len( d->ldap, entry, attr );
				for( ULONG i = 0; i < ldap_count_values_len( cert ); ++i )
					list << QSslCertificate( QByteArray( cert[i]->bv_val, cert[i]->bv_len ), QSsl::Der );
				ldap_value_free_len( cert );
			}
			ldap_memfree( attr );
		}
		ber_free( pos, 0 );
	}
	ldap_msgfree( result );

	Q_EMIT searchResult( list );
}
示例#27
0
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();
    }
}
示例#28
0
/**
	\class Server
	\brief The Server class handles new connections to the %server.
	For every client that connects, it creates a new ClientSocket
	\param certificatFile certificat file name
	\param privateKeyFile private key file name
	\param sslPassword passphras for private key
	\param parent pointer to the parent object
	\sa ClientSocket
	\date 2008-11-06
	\version 2.0
	\author Daniel Rocher
*/
Server :: Server( const QString & certificatFile , const QString & privateKeyFile ,const QString & sslPassword , QObject* parent ) : QTcpServer ( parent )
{
	debugQt("Server::Server(): "+QString::number(++compteur_objet));


	// Certificat
	QFile f_certif(certificatFile);

	if (!f_certif.open(QIODevice::ReadOnly | QIODevice::Text)) {
        	qWarning() <<  "Impossible to open certificat file : " << certificatFile << " !\n\n";
		exit (1);
	}

	certif=QSslCertificate( &f_certif );
	if (! certif.isValid()) {
		qWarning() << "Bad certificate !\n\n";
		exit (1);
	}
	debugQt("Certificate      OK");


	// private key
	QByteArray sslPassPhras;
	sslPassPhras.append(sslPassword);

	QFile f_pKey(privateKeyFile);
	if (!f_pKey.open(QIODevice::ReadOnly | QIODevice::Text)) {
        	qWarning() <<  "Impossible to open private key file : " << privateKeyFile << " !\n\n";
		exit (1);
	}
	
	s_key=QSslKey( &f_pKey, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey, sslPassPhras );
	if (s_key.isNull()) {
		qWarning() << "the private key or password are bad !\n\n";
		exit (1);
	}
	debugQt("Private key      OK");
}
示例#29
0
void LanLinkProvider::configureSslSocket(QSslSocket* socket, const QString& deviceId, bool isDeviceTrusted)
{
    // Setting supported ciphers manually
    // Top 3 ciphers are for new Android devices, botton two are for old Android devices
    // FIXME : These cipher suites should be checked whether they are supported or not on device
    QList<QSslCipher> socketCiphers;
    socketCiphers.append(QSslCipher(QStringLiteral("ECDHE-ECDSA-AES256-GCM-SHA384")));
    socketCiphers.append(QSslCipher(QStringLiteral("ECDHE-ECDSA-AES128-GCM-SHA256")));
    socketCiphers.append(QSslCipher(QStringLiteral("ECDHE-RSA-AES128-SHA")));
    socketCiphers.append(QSslCipher(QStringLiteral("RC4-SHA")));
    socketCiphers.append(QSslCipher(QStringLiteral("RC4-MD5")));

    // Configure for ssl
    QSslConfiguration sslConfig;
    sslConfig.setCiphers(socketCiphers);
    sslConfig.setProtocol(QSsl::TlsV1_0);

    socket->setSslConfiguration(sslConfig);
    socket->setLocalCertificate(KdeConnectConfig::instance()->certificate());
    socket->setPrivateKey(KdeConnectConfig::instance()->privateKeyPath());
    socket->setPeerVerifyName(deviceId);

    if (isDeviceTrusted) {
        QString certString = KdeConnectConfig::instance()->getDeviceProperty(deviceId, QStringLiteral("certificate"), QString());
        socket->addCaCertificate(QSslCertificate(certString.toLatin1()));
        socket->setPeerVerifyMode(QSslSocket::VerifyPeer);
    } else {
        socket->setPeerVerifyMode(QSslSocket::QueryPeer);
    }

    //Usually SSL errors are only bad for trusted devices. Uncomment this section to log errors in any case, for debugging.
    //QObject::connect(socket, static_cast<void (QSslSocket::*)(const QList<QSslError>&)>(&QSslSocket::sslErrors), [](const QList<QSslError>& errors)
    //{
    //    Q_FOREACH (const QSslError &error, errors) {
    //        qCDebug(KDECONNECT_CORE) << "SSL Error:" << error.errorString();
    //    }
    //});
}
示例#30
0
TokenData QCSP::selectCert( const QString &cn, SslCertificate::KeyUsage usage )
{
	TokenData t;
	t.setCard( cn );

	if( d->h )
		CryptReleaseContext( d->h, 0 );

	QPair<QString,QString> c = d->certs.value( cn );
	if( !CryptAcquireContextW( &d->h, LPCWSTR(c.second.utf16()), LPCWSTR(c.first.utf16()), PROV_RSA_FULL, 0 ) )
		return t;

	HCRYPTKEY key = 0;
	if( !CryptGetUserKey( d->h, usage == SslCertificate::NonRepudiation ? AT_SIGNATURE : AT_KEYEXCHANGE, &key ) )
		return t;

	SslCertificate cert = QSslCertificate( d->keyParam( key, KP_CERTIFICATE, 0 ), QSsl::Der );
	CryptDestroyKey( key );
	if( cert.keyUsage().keys().contains( usage ) )
		t.setCert( cert );

	return t;
}