Petr
Petr

Reputation: 14485

How to ignore SSL error in Qt based TCP server - client application

I am implementing client - server application that uses TCP for communication. I would like to use SSL to improve security, but I need to make it possible for client to connect even to servers with self signed or "not-very-secure" certificates. Right now I created some random test certificate and I am trying to use it on my local machine (both server and client runs there, no server host resolution can be done, it's simply localhost).

I am keep on getting this error on client side:

Socket error: The host name did not match any of the valid hosts for this certificate

I am trying to suppress this by using this code:

    // We don't care about self signed certificates
    QList<QSslError> errors;
    errors << QSslError(QSslError::SelfSignedCertificate);
    errors << QSslError(QSslError::HostNameMismatch);
    ((QSslSocket*)this->socket)->ignoreSslErrors(errors);
    ((QSslSocket*)this->socket)->connectToHostEncrypted(this->hostname, this->port);

However it doesn't work, no matter if I use this code before or after connection, it still fails because of the "didn't match" error.

How do I tell the QSslSocket "dear socket, I don't care at all if the certificate is self signed or doesn't match the valid host, just connect me please"?

Upvotes: 2

Views: 3116

Answers (1)

Petr
Petr

Reputation: 14485

So, I figured it out:

The ignoreSslErrors with parameters works only if you specify a certificate in a constructor of the class.

An alternative is a call to ignoreSslErrors() without parameters. This function however needs to be called from a Qt slot connected to signal sslErrors. It's not explained why is that required by it doesn't seem to work any other way.

Documentation: http://doc.qt.io/qt-5/qsslsocket.html#ignoreSslErrors-1

Working example

void Program::OnSslHandshakeFailure(QList<QSslError> errors)
{
    this->socket->ignoreSslErrors();
}

void Program::Connect()
{
    connect(this->socket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(OnSslHandshakeFailure(QList<QSslError>)));
    this->socket->connectToHostEncrypted(this->hostname, this->port);
}

Upvotes: 3

Related Questions