tioo
tioo

Reputation: 99

Why can not I get the right information about the certificate, which is used by the user?

There are two completely different sites. They have 2 different ssl certificate. Described below program acts as a server. The client is a browser. When I go to diferent sites serviced my https server, I get constantly one hash.

    #include <QCoreApplication>
    #include "server.h"

    int main(int argc, char *argv[]) {
        QCoreApplication a(argc, argv);
        Server h;
        return a.exec();
    }

    ///////////////////////////////////////

    #ifndef SERVER_H
    #define SERVER_H

    #include <QTcpServer>

    class Server : public QTcpServer {
        public:
        Server();

        void incomingConnection(int);
    };

    #endif // SERVER_H


    ///////////////////////////////////////////

    #include "server.h"

    #include <QSslSocket>
    #include <QSslCertificate>

    Server::Server() {
        if (!listen(QHostAddress::Any, 80)) {
            //error
        }
    }

    void Server::incomingConnection(int d) {
        QSslSocket * socket = new QSslSocket();
        if(socket->setSocketDescriptor(d)) {
            socket->setProtocol(QSsl::AnyProtocol);
            //always one hash. why?
            qDebug() << socket->peerCertificate().digest(QCryptographicHash::Sha1).toHex();
            QString c, k;
            c = "site.crt";
            k = "site.key";
            socket->setLocalCertificate(c);
            socket->setPrivateKey(k);
            socket->startServerEncryption();
            if(socket->waitForEncrypted()) {
                if(socket->waitForReadyRead()) {
                    socket->write(socket->readAll());
                    socket->waitForBytesWritten();
                    socket->disconnectFromHost();
                    if(socket->state() == QTcpSocket::UnconnectedState) {
                        socket->waitForDisconnected();
                    }
                    socket->close();
                    socket->deleteLater();
                }
                else {
                    delete socket;
                }
            }
            else {
                delete socket;
            }
        }
    }

Upvotes: 0

Views: 121

Answers (1)

Nejat
Nejat

Reputation: 32675

From the Qt documentation:

Because the peer certificate is set during the handshake phase, it is safe to access the peer certificate from a slot connected to the sslErrors() signal or the encrypted() signal.

If a null certificate is returned, it can mean the SSL handshake failed, or it can mean the host you are connected to doesn't have a certificate, or it can mean there is no connection.

So you should try to get the client certificate after receiving the QSslSocket::encrypted signal in a local slot.

You should also note that if your client does not have a certificate then peerCertificate() will return a null value.

Upvotes: 1

Related Questions