Home

QtSslSocket Class Reference

The QtSslSocket class provides a TCP socket with SSL encryption support. More...

    #include <QtSslSocket>

Inherits QTcpSocket.

Public Types

Public Functions

Public Slots

Signals

Protected Slots

Additional Inherited Members


Detailed Description

The QtSslSocket class provides a TCP socket with SSL encryption support.

It provides some extra functionality which is needed for working with SSL, but otherwise there is no difference from QTcpSocket. Example:

    void MyClient::connectToHost(const QString &host, int port)
    {
        // Create a new SSL socket
        socket = new QtSslSocket();

        // Set the path to the CA certificates
        socket->setPathToCACertDir("/etc/ssl/certs/");

        // Connect the socket's signals to slots in our client
        // implementation.
        connect(socket, SIGNAL(connected()),
                this, SLOT(connectedToHost()));
        connect(socket, SIGNAL(readyRead()),
                this, SLOT(readData()));
        connect(socket, SIGNAL(disconnected()),
                this, SLOT(connectionClosed()));
        connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
                this, SLOT(inspectError(QAbstractSocket::SocketError)));
        connect(socket, SIGNAL(connectionVerificationDone(QtSslSocket::VerifyResult, bool, const QString &)),
                this, SLOT(checkCertError(QtSslSocket::VerifyResult, bool, const QString &)));

        // Initiate a connection.
        socket->connectToHost(host, port);
    }

Use connectToHost() when connecting to an SSL server. QtSslSocket will eventually emit the connected() signal if the connection was established, or the error() signal if the connection failed.

In the case of accepting incoming connections, one common approach is to create a subclass of QTcpServer and reimplement QTcpServer::incomingConnection(). In this function, create a QtSslSocket object and call setSocketDescriptor() passing the provided socketDescriptor. Connect QtSslSocket's signals to slots in the server class. The path to a file containing a PEM encoded certificate is set with setPathToCertificate(). The path to the private key file is set with setPathToPrivateKey(). Finally, call sslAccept() to establish the secure connection. When QtSslSocket emits connectionVerificationDone(), the SSL encrypted link is established. Example:

    void MyServer::incomingConnection(int socketDescriptor)
    {
        // Create a new socket and pass it a new QSocket
        socket = new QtSslSocket(QtSslSocket::Server, this);
        socket->setSocketDescriptor(socketDescriptor);

        // Set up the certificate and private key.
        socket->setPathToCertificate("/etc/ssl/servercert.pem");
        socket->setPathToPrivateKey("/etc/ssl/serverkey.pem");

        // Connect the socket's signals to slots in our server
        // implementation
        connect(socket, SIGNAL(disconnected()),
                this, SLOT(connectionClosed()));
        connect(socket, SIGNAL(readyRead()),
                this, SLOT(readData()));
        connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
                this, SLOT(error(QAbstractSocket::SocketError)));

        // Initiate SSL handshake. Eventually, QtSslSocket will emit
        // connectionVerificationDone.
        socket->sslAccept();
    }

In order to convert an existing socket into an SSL-encrypted socket (i.e., using the "STARTTLS" command or something similar), you can create a new QtSslSocket and then pass your existing socket to setSocket(). The original socket is assumed to be in ConnectedState.

Most often clients, but sometimes also servers need a set of CA (Certificate Authority) certificates to verify the identity of their peer. Use setPathToCACertFile() and setPathToCACertDir() to point QtSslSocket to these certificates. CA certificates are usually bundled as part of any Unix distribution or Mac OS X as part of the OpenSSL package. On Windows, you can either use the bundle provided with OpenSSL, or export CA certificates from your web browser.

In rare occasions, it also is useful to restrict the encryption ciphers available to the client or server with setCiphers(). This is mostly useful when debugging faulty connections.

As mentioned, QtSslSocket emits connected() when the connection has been established and connectionVerificationDone() when the SSL handshake has been completed. Make sure to connect to error() and connectionVerificationDone() to catch errors. The readyRead() signal is emitted when there is new incoming data. Call read() to read the new data into a buffer. When disconnected() is emitted, the other peer has closed the connection.

If the ceritificate check fails, it is often useful to display details about the failing certificate to the user. peerCertificate() returns information about this certificate. To get the local certificate, call localCertificate().

When building an application that uses QtSslSocket, you must link your application against the SSL library. Include the bundled .pri file, or add the following line to your .pro file, modified with the path to your installation of OpenSSL:

    unix:LIBS += -L/usr/lib -lssl -lcrypto
    win32:INCLUDEPATH += /openssl/include
    win32:LIBS += -L/openssl/lib ssleay32.lib libeay32.lib

The pri file must be edited to set the paths of the SSL files.

Note: QtSslSocket requires OpenSSL. The OpenSSL toolkit is licensed under an Apache-style licence, which basically means that you are free to get and use it for commercial and non-commercial purposes subject to certain license conditions. The official web site is: http://www.openssl.org/ . Windows binaries are available from: http://www.openssl.org/related/binaries.html .

Note: Since Qt 4.1, you can pass a QtSslSocket to QHttp by calling QHttp::setSocket() to achieve an SSL encrypted HTTP transport. (SSL over HTTP uses port 443.)

See also QTcpSocket and QTcpServer.


Member Type Documentation

enum QtSslSocket::Mode

Describes whether QtSslSocket is used on the client side or the server side. Pass a suitable value to QtSslSocket's constructor to ensure that the SSL handshake is performed correctly.

ConstantValueDescription
QtSslSocket::Client0QtSslSocket is used for a client side socket (i.e., you call connectToHost() to connect to a remote SSL server.
QtSslSocket::Server1QtSslSocket is used to handle a server side connection (i.e., someone connected to your server).

enum QtSslSocket::VerifyResult

Describes the result of the SSL handshake.

ConstantValueDescription
QtSslSocket::VerifyOk0The certificate has been successfully verified, and the peer authenticity has been established. The connection is secure, and ready to use.
QtSslSocket::SelfSigned1The peer certificate is self-signed (i.e., does not use a certificate authority for verification). This means that the identity of the peer has not been established. Self-signed peer certificates provide no security beyond transport encryption, and should only be used on closed networks or for debugging.
QtSslSocket::Expired2The peer certificate has expired. This means that the associated certificate authority no longer guarantees the identity of the peer. An expired certificate provides no security beyond transport encryption, and the administrators of the remote server should be notified as soon as possible.
QtSslSocket::NotYetValid3The peer certificate is not valid yet (i.e., the "opposite" of Expired). It provides no security beyond transport encryption, and the administrators of the remote server should be notified as soon as possible.
QtSslSocket::UnableToVerify4This value signifies an error that was not covered by the other (non-VerifyOK) VerifyResult values. A common cause for the UnableToVerify value is that there is a technical fault on either side of the connection that prevents the handshake from completing, such as the server running out of diskspace, or the client running out of memory.


Member Function Documentation

QtSslSocket::QtSslSocket ( Mode mode = Client, QObject * parent = 0 )

Constructs a QtSslSocket running with mode mode. parent is passed to QTcpSocket's constructor.

QtSslSocket::~QtSslSocket ()

Destroys the QtSslSocket object.

QString QtSslSocket::ciphers () const

Returns the list of ciphers QtSslSocket will advertise to the remote peer during the SSL handshake.

See also setCiphers().

void QtSslSocket::connectToHost ( const QString & hostName, quint16 port, OpenMode openMode = QIODevice::ReadWrite )

Initiates a connection to hostName on port port, using the open mode openMode. QtSslSocket will emit connected() when the connection has been established, and connectionVerificationDone() when the SSL handshake has completed and the socket is ready to use.

Note: The implementation of this function invokes the slot connectToHostImplementation(). To alter its behavior, you should reimplement connectToHostImplementation() instead.

void QtSslSocket::connectToHostImplementation ( const QString & hostName, quint16 port, OpenMode openMode )   [protected slot]

Initiates a connection to the host hostName on port port, using the open mode openMode. After QtSslSocket emits connected(), the SSL handshake will start automatically, and eventually QtSslSocket will emit connectionVerificationDone() to signal that the handshake has completed. It is essential that the connection is not used before the handshake has completed.

Note: This function contains the implementation of connectToHost(). It is implemented as a slot to achieve polymorphic behavior (as QTcpSocket::connectToHost() is not virtual). Reimplement this function to alter the behavior of connectToHost() polymorphically.

See also disconnectFromHostImplementation().

void QtSslSocket::connectionVerificationDone ( QtSslSocket::VerifyResult result, bool hostNameMatched, const QString & description )   [signal]

This signal is emitted by QtSslSocket to notify that the SSL handshake has completed, and the connecion is ready for use. The result of the handshake is available through result, and in addition, hostNameMatched will be set to true if the hostname of the peer certificate matches the hostname passed to connectToHost(), or false if it doesn't. (For server-side connections, hostNameMatched is always true.) For displaying to the user, description contains a human readable description of the result of the certificate verification.

void QtSslSocket::disconnectFromHost ()

Initiates a disconnect from the remote host.

Note: The implementation of this function invokes the disconnectFromHostImplementation() slot.

void QtSslSocket::disconnectFromHostImplementation ()   [protected slot]

This function contains the implementation of disconnectFromHost(). It is implemented as a slot to achieve polymorphic behavior (as QTcpSocket::disconnectFromHost() is not virtual). Reimplement this function to alter the behavior of disconnectFromHost() polymorphically.

See also connectToHostImplementation().

QString QtSslSocket::localCertificate () const

Returns the local SSL certificate as a list of keys and values, separated by '/'. Call this function after the connection has been established and connectionVerificationDone() has been emitted to show the user the details of the certificate. This function is usually only called in the case where the SSL verification failed. If you call this function on an unconnected socket, or before QtSslSocket emits connectionVerificationDone(), or without providing QtSslSocket with a local certificate (see setPathToCertificate()), it will return an empty string.

See also peerCertificate().

QString QtSslSocket::pathToCACertDir () const

Returns the path to a locale directory containing files with CA certificates.

See also setPathToCACertDir().

QString QtSslSocket::pathToCACertFile () const

Returns the path to a local file containing a bundle of CA certificates.

See also setPathToCACertFile().

QString QtSslSocket::pathToCertificate () const

Returns the path to the client's certificate.

See also setPathToCertificate().

QString QtSslSocket::pathToPrivateKey () const

Returns the path to the client's private key.

See also setPathToPrivateKey().

QString QtSslSocket::peerCertificate () const

Returns the peer SSL certificate as a list of keys and values, separated by '/'. Call this function after the connection has been established and connectionVerificationDone() has been emitted to show the user the details of the peer certificate. This function is usually only called in the case where the SSL verification failed. If you call this function on an unconnected socket, or before QtSslSocket emits connectionVerificationDone(), it will return an empty string.

See also localCertificate().

void QtSslSocket::setCiphers ( const QString & ciphers )

Sets the list of ciphers QtSslSocket will advertise to the remote peer during the SSL handshake. This effectively limits the ciphers QtSslSocket can use, and is therefore mostly useful for debugging the SSL handshake. ciphers contains a list of ciphers listed by name, separated by a ':', and listed in descending order from the most secure to the least secure cipher.

The default behavior for QtSslSocket is to advertise all available ciphers to the remote peer, thereby maximizing the chance that a secure connection can be established.

See also ciphers().

void QtSslSocket::setPathToCACertDir ( const QString & path )

Sets the path to a local directory containing files with CA certificates to path. This directory is generated by OpenSSL using the program "c_rehash", and is often installed by default as part of installing OpenSSL. It's common to use a CA directory containing several CA files instead of using only a single CA file, as you can then add more CA files without interfering with ones provided by the operating system, your web browser or by OpenSSL.

See also pathToCACertDir() and setPathToCACertFile().

void QtSslSocket::setPathToCACertFile ( const QString & path )

Sets the path to a local file containing a bundle of CA certificates to path. You can either use the bundle that comes with OpenSSL, or use a bundle exported by your web browser. This CA bundle is necessary for verifying the authenticity of the remote peer. Without such a bundle, QtSslSocket can never verify the peer's identity, but it will still encrypt the transferred data.

See also pathToCACertFile() and Guide to SSL certificates and certificate authorities.

void QtSslSocket::setPathToCertificate ( const QString & path )

Sets the path to a local file containing the client's certificate to path. This is useful for server side connections, or for clients that connect to servers that need to verify the peer identity (client verification is not yet supported by QtSslSocket).

See also pathToCertificate().

void QtSslSocket::setPathToPrivateKey ( const QString & path )

Sets the path the a local file containing the client's private key to path. This is useful for server side connections, or for clients that connect to servers that need to verify the peer identity (client verification is not yet supported by QtSslSocket).

See also pathToPrivateKey().

void QtSslSocket::setSocket ( QTcpSocket * socket )

Sets or replaces QtSslSocket's internal socket with socket. socket must be in ConnectedState; otherwise this function does nothing. After calling setSocket(), you can call sslConnect() to initiate a client-side handshake, or sslAccept() to initiate a server-side handshake.

QtSslSocket disconnects all socket's existing signal connections as part of the handover, but does not take ownership of the object (i.e., the object is not deleted when QtSslSocket is deleted).

This functionality is useful if you need to enable SSL on an existing, unencrypted socket. For example, certain network protocols like IMAP4, POP3 and SMTP allow you to use a plain text connection initially, and then convert to an encrypted connection later by issuing a certain command (e.g., "STARTTLS"). Example:

    void NetworkProtocol::readyReadSlot()
    {
        // Convert to an SSL connection.
        if (socket->canReadLine() && socket->readLine() == "STARTTLS\r\n") {
            QtSslSocket *sslSocket = new QtSslSocket(QtSslSocket::Client, this);
            sslSocket->setSocket(socket);
            socket = sslSocket;
            connectSignals(socket);
        }
    }

See also socket().

QTcpSocket * QtSslSocket::socket () const

Returns a pointer to the socket holding the actualy SSL connection. This is different from QtSslSocket, which only acts like a wrapper. Call this function if you need to access the actual connected socket.

See also setSocket().

bool QtSslSocket::sslAccept ()   [slot]

Initiates the SSL handshake for server-side sockets (Server). This function is useful for when QtSslSocket is initialized using setSocketDescriptor(). After calling sslAccept(), QtSslSocket will eventually emit connectionVerificationDone().

See also sslConnect().

bool QtSslSocket::sslConnect ()   [slot]

Initiates the SSL handshake for client-side sockets (Client). This function is useful for when QtSslSocket is initialized using setSocketDescriptor(). After calling sslConnect(), QtSslSocket will eventually emit connectionVerificationDone().

If you connect to a peer by calling connectToHost(), you do not need to call this function as QtSslSocket will do so for you.

See also sslAccept().


Copyright © 2008 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions