Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
QDtlsClientVerifier Class Reference

This class implements server-side DTLS cookie generation and verification. More...

#include <qdtls.h>

+ Inheritance diagram for QDtlsClientVerifier:
+ Collaboration diagram for QDtlsClientVerifier:

Classes

class  GeneratorParameters
 This class defines parameters for DTLS cookie generator. More...
 

Public Member Functions

 QDtlsClientVerifier (QObject *parent=nullptr)
 Constructs a QDtlsClientVerifier object, parent is passed to QObject's constructor.
 
 ~QDtlsClientVerifier ()
 Destroys the QDtlsClientVerifier object.
 
bool setCookieGeneratorParameters (const GeneratorParameters &params)
 Sets the secret and the cryptographic hash algorithm from params.
 
GeneratorParameters cookieGeneratorParameters () const
 Returns the current secret and hash algorithm used to generate cookies.
 
bool verifyClient (QUdpSocket *socket, const QByteArray &dgram, const QHostAddress &address, quint16 port)
 socket must be a valid pointer, dgram must be a non-empty datagram, address cannot be null, broadcast, or multicast.
 
QByteArray verifiedHello () const
 Convenience function.
 
QDtlsError dtlsError () const
 Returns the last error that occurred or QDtlsError::NoError.
 
QString dtlsErrorString () const
 Returns a textual description of the last error, or an empty string.
 
- Public Member Functions inherited from QObject
Q_INVOKABLE QObject (QObject *parent=nullptr)
 Constructs an object with parent object parent.
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects.
 
virtual bool event (QEvent *event)
 This virtual function receives events to an object and should return true if the event e was recognized and processed.
 
virtual bool eventFilter (QObject *watched, QEvent *event)
 Filters events if this object has been installed as an event filter for the watched object.
 
QString objectName () const
 
Q_WEAK_OVERLOAD void setObjectName (const QString &name)
 Sets the object's name to name.
 
void setObjectName (QAnyStringView name)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
QBindable< QStringbindableObjectName ()
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false.
 
bool isWindowType () const
 Returns true if the object is a window; otherwise returns false.
 
bool isQuickItemType () const
 Returns true if the object is a QQuickItem; otherwise returns false.
 
bool signalsBlocked () const noexcept
 Returns true if signals are blocked; otherwise returns false.
 
bool blockSignals (bool b) noexcept
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it).
 
QThreadthread () const
 Returns the thread in which the object lives.
 
bool moveToThread (QThread *thread QT6_DECL_NEW_OVERLOAD_TAIL)
 Changes the thread affinity for this object and its children and returns true on success.
 
int startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer)
 This is an overloaded function that will start a timer of type timerType and a timeout of interval milliseconds.
 
int startTimer (std::chrono::nanoseconds time, Qt::TimerType timerType=Qt::CoarseTimer)
 
void killTimer (int id)
 Kills the timer with timer identifier, id.
 
void killTimer (Qt::TimerId id)
 
template<typename T >
findChild (QAnyStringView aName, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 Returns the child of this object that can be cast into type T and that is called name, or \nullptr if there is no such object.
 
template<typename T >
QList< T > findChildren (QAnyStringView aName, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects.
 
template<typename T >
findChild (Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
template<typename T >
QList< T > findChildren (Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
const QObjectListchildren () const
 Returns a list of child objects.
 
void setParent (QObject *parent)
 Makes the object a child of parent.
 
void installEventFilter (QObject *filterObj)
 Installs an event filter filterObj on this object.
 
void removeEventFilter (QObject *obj)
 Removes an event filter object obj from this object.
 
QMetaObject::Connection connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=nullptr, const QObject *receiver=nullptr, const char *member=nullptr) const
 
bool disconnect (const QObject *receiver, const char *member=nullptr) const
 
void dumpObjectTree () const
 Dumps a tree of children to the debug output.
 
void dumpObjectInfo () const
 Dumps information about signal connections, etc.
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value.
 
bool setProperty (const char *name, QVariant &&value)
 
QVariant property (const char *name) const
 Returns the value of the object's name property.
 
QList< QByteArraydynamicPropertyNames () const
 
QBindingStoragebindingStorage ()
 
const QBindingStoragebindingStorage () const
 
QObjectparent () const
 Returns a pointer to the parent object.
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false.
 

Additional Inherited Members

- Public Slots inherited from QObject
void deleteLater ()
 \threadsafe
 
- Signals inherited from QObject
void destroyed (QObject *=nullptr)
 This signal is emitted immediately before the object obj is destroyed, after any instances of QPointer have been notified, and cannot be blocked.
 
void objectNameChanged (const QString &objectName, QPrivateSignal)
 This signal is emitted after the object's name has been changed.
 
- Static Public Member Functions inherited from QObject
static QMetaObject::Connection connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 \threadsafe
 
static QMetaObject::Connection connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
template<typename Func1 , typename Func2 >
static QMetaObject::Connection connect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const typename QtPrivate::ContextTypeForFunctor< Func2 >::ContextType *context, Func2 &&slot, Qt::ConnectionType type=Qt::AutoConnection)
 
template<typename Func1 , typename Func2 >
static QMetaObject::Connection connect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, Func2 &&slot)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 \threadsafe
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static bool disconnect (const QMetaObject::Connection &)
 Disconnect a connection.
 
template<typename Func1 , typename Func2 >
static bool disconnect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const typename QtPrivate::FunctionPointer< Func2 >::Object *receiver, Func2 slot)
 
template<typename Func1 >
static bool disconnect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const QObject *receiver, void **zero)
 
- Protected Member Functions inherited from QObject
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns \nullptr.
 
int senderSignalIndex () const
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal.
 
bool isSignalConnected (const QMetaMethod &signal) const
 
virtual void timerEvent (QTimerEvent *event)
 This event handler can be reimplemented in a subclass to receive timer events for the object.
 
virtual void childEvent (QChildEvent *event)
 This event handler can be reimplemented in a subclass to receive child events.
 
virtual void customEvent (QEvent *event)
 This event handler can be reimplemented in a subclass to receive custom events.
 
virtual void connectNotify (const QMetaMethod &signal)
 
virtual void disconnectNotify (const QMetaMethod &signal)
 
 QObject (QObjectPrivate &dd, QObject *parent=nullptr)
 
- Protected Attributes inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Properties inherited from QObject
QString objectName
 the name of this object
 

Detailed Description

This class implements server-side DTLS cookie generation and verification.

Since
5.12

\inmodule QtNetwork

The QDtlsClientVerifier class implements server-side DTLS cookie generation and verification. Datagram security protocols are highly susceptible to a variety of Denial-of-Service attacks. According to \l {RFC 6347, section 4.2.1}, these are two of the more common types of attack:

\list

  • An attacker transmits a series of handshake initiation requests, causing a server to allocate excessive resources and potentially perform expensive cryptographic operations.
  • An attacker transmits a series of handshake initiation requests with a forged source of the victim, making the server act as an amplifier. Normally, the server would reply to the victim machine with a Certificate message, which can be quite large, thus flooding the victim machine with datagrams. \endlist

As a countermeasure to these attacks, \l {RFC 6347, section 4.2.1} proposes a stateless cookie technique that a server may deploy:

\list

  • In response to the initial ClientHello message, the server sends a HelloVerifyRequest, which contains a cookie. This cookie is a cryptographic hash and is generated using the client's address, port number, and the server's secret (which is a cryptographically strong pseudo-random sequence of bytes).
  • A reachable DTLS client is expected to reply with a new ClientHello message containing this cookie.
  • When the server receives the ClientHello message with a cookie, it generates a new cookie as described above. This new cookie is compared to the one found in the ClientHello message.
  • In the cookies are equal, the client is considered to be real, and the server can continue with a TLS handshake procedure. \endlist
Note
A DTLS server is not required to use DTLS cookies.

QDtlsClientVerifier is designed to work in pair with QUdpSocket, as shown in the following code-excerpt:

class DtlsServer : public QObject
{
public:
// ...
private:
void readyRead();
// ...
QUdpSocket serverSocket;
// ...
};
bool DtlsServer::listen(const QHostAddress &serverAddress, quint16 serverPort)
{
if (serverSocket.bind(serverAddress, serverPort))
connect(&serverSocket, &QUdpSocket::readyRead, this, &DtlsServer::readyRead);
return serverSocket.state() == QAbstractSocket::BoundState;
}
void DtlsServer::readyRead()
{
quint16 port = {};
serverSocket.readDatagram(dgram.data(), dgram.size(), &address, &port);
if (verifiedClients.contains({address, port}) {
// This client was verified previously, we either continue the
// handshake or decrypt the incoming message.
} else if (verifier.verifyClient(&serverSocket, dgram, address, port)) {
// Apparently we have a real DTLS client who wants to send us
// encrypted datagrams. Remember this client as verified
// and proceed with a handshake.
} else {
// No matching cookie was found in the incoming datagram,
// verifyClient() has sent a ClientVerify message.
// We'll hear from the client again soon, if they're real.
}
}

QDtlsClientVerifier does not impose any restrictions on how the application uses QUdpSocket. For example, it is possible to have a server with a single QUdpSocket in state QAbstractSocket::BoundState, handling multiple DTLS clients simultaneously:

\list

  • Testing if new clients are real DTLS-capable clients.
  • Completing TLS handshakes with the verified clients (see QDtls).
  • Decrypting datagrams coming from the connected clients (see QDtls).
  • Sending encrypted datagrams to the connected clients (see QDtls). \endlist

This implies that QDtlsClientVerifier does not read directly from a socket, instead it expects the application to read an incoming datagram, extract the sender's address, and port, and then pass this data to verifyClient(). To send a HelloVerifyRequest message, verifyClient() can write to the QUdpSocket.

Note
QDtlsClientVerifier does not take ownership of the QUdpSocket object.

By default QDtlsClientVerifier obtains its secret from a cryptographically strong pseudorandom number generator.

Note
The default secret is shared by all objects of the classes QDtlsClientVerifier and QDtls. Since this can impose security risks, RFC 6347 recommends to change the server's secret frequently. Please see \l {RFC 6347, section 4.2.1} for hints about possible server implementations. Cookie generator parameters can be set using the class QDtlsClientVerifier::GeneratorParameters and setCookieGeneratorParameters():
void DtlsServer::updateServerSecret()
{
const QByteArray newSecret(generateCryptoStrongSecret());
if (newSecret.size()) {
usedCookies.append(newSecret);
}
}

The \l{secureudpserver}{DTLS server} example illustrates how to use QDtlsClientVerifier in a server application.

See also
QUdpSocket, QAbstractSocket::BoundState, QDtls, verifyClient(), GeneratorParameters, setCookieGeneratorParameters(), cookieGeneratorParameters(), QDtls::setCookieGeneratorParameters(), QDtls::cookieGeneratorParameters(), QCryptographicHash::Algorithm, QDtlsError, dtlsError(), dtlsErrorString()

Definition at line 43 of file qdtls.h.

Constructor & Destructor Documentation

◆ QDtlsClientVerifier()

QDtlsClientVerifier::QDtlsClientVerifier ( QObject * parent = nullptr)
explicit

Constructs a QDtlsClientVerifier object, parent is passed to QObject's constructor.

Definition at line 354 of file qdtls.cpp.

References d, and QSslSocket::VerifyNone.

◆ ~QDtlsClientVerifier()

QDtlsClientVerifier::~QDtlsClientVerifier ( )

Destroys the QDtlsClientVerifier object.

Definition at line 372 of file qdtls.cpp.

Member Function Documentation

◆ cookieGeneratorParameters()

QDtlsClientVerifier::GeneratorParameters QDtlsClientVerifier::cookieGeneratorParameters ( ) const

Returns the current secret and hash algorithm used to generate cookies.

The default hash algorithm is QCryptographicHash::Sha256 if Qt was configured to support it, QCryptographicHash::Sha1 otherwise. The default secret is obtained from the backend-specific cryptographically strong pseudorandom number generator.

See also
QCryptographicHash::Algorithm, QDtlsClientVerifier::GeneratorParameters, setCookieGeneratorParameters()

Definition at line 406 of file qdtls.cpp.

References d.

◆ dtlsError()

QDtlsError QDtlsClientVerifier::dtlsError ( ) const

Returns the last error that occurred or QDtlsError::NoError.

See also
QDtlsError, dtlsErrorString()

Definition at line 476 of file qdtls.cpp.

References d, and TlsInitializationError.

◆ dtlsErrorString()

QString QDtlsClientVerifier::dtlsErrorString ( ) const

Returns a textual description of the last error, or an empty string.

See also
dtlsError()

Definition at line 491 of file qdtls.cpp.

References d, and QStringLiteral.

◆ setCookieGeneratorParameters()

bool QDtlsClientVerifier::setCookieGeneratorParameters ( const GeneratorParameters & params)

Sets the secret and the cryptographic hash algorithm from params.

This QDtlsClientVerifier will use these to generate cookies. If the new secret has size zero, this function returns false and does not change the cookie generator parameters.

Note
The secret is supposed to be a cryptographically secure sequence of bytes.
See also
QDtlsClientVerifier::GeneratorParameters, cookieGeneratorParameters(), QCryptographicHash::Algorithm

Definition at line 387 of file qdtls.cpp.

References d.

◆ verifiedHello()

QByteArray QDtlsClientVerifier::verifiedHello ( ) const

Convenience function.

Returns the last ClientHello message that was successfully verified, or an empty QByteArray if no verification has completed.

See also
verifyClient()

Definition at line 461 of file qdtls.cpp.

References d.

◆ verifyClient()

bool QDtlsClientVerifier::verifyClient ( QUdpSocket * socket,
const QByteArray & dgram,
const QHostAddress & address,
quint16 port )

socket must be a valid pointer, dgram must be a non-empty datagram, address cannot be null, broadcast, or multicast.

port is the remote peer's port. This function returns true if dgram contains a ClientHello message with a valid cookie. If no matching cookie is found, verifyClient() will send a HelloVerifyRequest message using socket and return false.

The following snippet shows how a server application may check for errors:

if (!verifier.verifyClient(&socket, message, address, port)) {
switch (verifyClient.dtlsError()) {
// Not verified yet, but no errors found and we have to wait for the next
// message from this client.
return;
// This error is fatal, nothing we can do about it.
// Probably, quit the server after reporting the error.
return;
// There is some problem in QUdpSocket, handle it (see QUdpSocket::error())
return;
default:
Q_UNREACHABLE();
}
}
bool listen(const QHostAddress &address, quint16 port)
virtual bool bind(const QHostAddress &address, quint16 port=0, BindMode mode=DefaultForPlatform)
This class implements server-side DTLS cookie generation and verification.
Definition qdtls.h:44
bool verifyClient(QUdpSocket *socket, const QByteArray &dgram, const QHostAddress &address, quint16 port)
socket must be a valid pointer, dgram must be a non-empty datagram, address cannot be null,...
Definition qdtls.cpp:431
bool setCookieGeneratorParameters(const GeneratorParameters &params)
Sets the secret and the cryptographic hash algorithm from params.
Definition qdtls.cpp:387
void readyRead()
This signal is emitted once every time new data is available for reading from the device's current re...
qint64 readDatagram(char *data, qint64 maxlen, QHostAddress *host=nullptr, quint16 *port=nullptr)
Receives a datagram no larger than maxSize bytes and stores it in data.
qint64 pendingDatagramSize() const
Returns the size of the first pending UDP datagram.
@ TlsInitializationError
@ UnderlyingSocketError
@ InvalidInputParameters
unsigned short quint16
Definition qtypes.h:48
socketLayer listen()
See also
QHostAddress::isNull(), QHostAddress::isBroadcast(), QHostAddress::isMulticast(), setCookieGeneratorParameters(), cookieGeneratorParameters()

Definition at line 431 of file qdtls.cpp.

References d, InvalidInputParameters, msgUnsupportedMulticastAddress(), QByteArray::size(), socket, and tr.

+ Here is the call graph for this function:

The documentation for this class was generated from the following files: