Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
src_network_ssl_qdtlscookie.cpp
Go to the documentation of this file.
1// Copyright (C) 2018 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3
4//! [0]
5class DtlsServer : public QObject
6{
7public:
8 bool listen(const QHostAddress &address, quint16 port);
9 // ...
10
11private:
12 void readyRead();
13 // ...
14
15 QUdpSocket serverSocket;
16 QDtlsClientVerifier verifier;
17 // ...
18};
19
20bool DtlsServer::listen(const QHostAddress &serverAddress, quint16 serverPort)
21{
22 if (serverSocket.bind(serverAddress, serverPort))
23 connect(&serverSocket, &QUdpSocket::readyRead, this, &DtlsServer::readyRead);
24 return serverSocket.state() == QAbstractSocket::BoundState;
25}
26
27void DtlsServer::readyRead()
28{
29 QByteArray dgram(serverSocket.pendingDatagramSize(), Qt::Uninitialized);
30 QHostAddress address;
31 quint16 port = {};
32 serverSocket.readDatagram(dgram.data(), dgram.size(), &address, &port);
33 if (verifiedClients.contains({address, port}) {
34 // This client was verified previously, we either continue the
35 // handshake or decrypt the incoming message.
36 } else if (verifier.verifyClient(&serverSocket, dgram, address, port)) {
37 // Apparently we have a real DTLS client who wants to send us
38 // encrypted datagrams. Remember this client as verified
39 // and proceed with a handshake.
40 } else {
41 // No matching cookie was found in the incoming datagram,
42 // verifyClient() has sent a ClientVerify message.
43 // We'll hear from the client again soon, if they're real.
44 }
45}
46//! [0]
47
48//! [1]
49void DtlsServer::updateServerSecret()
50{
51 const QByteArray newSecret(generateCryptoStrongSecret());
52 if (newSecret.size()) {
53 usedCookies.append(newSecret);
54 verifier.setCookieGeneratorParameters({QCryptographicHash::Sha1, newSecret});
55 }
56}
57//! [1]
58
59//! [2]
60if (!verifier.verifyClient(&socket, message, address, port)) {
61 switch (verifyClient.dtlsError()) {
62 case QDtlsError::NoError:
63 // Not verified yet, but no errors found and we have to wait for the next
64 // message from this client.
65 return;
66 case QDtlsError::TlsInitializationError:
67 // This error is fatal, nothing we can do about it.
68 // Probably, quit the server after reporting the error.
69 return;
70 case QDtlsError::UnderlyingSocketError:
71 // There is some problem in QUdpSocket, handle it (see QUdpSocket::error())
72 return;
73 case QDtlsError::InvalidInputParameters:
74 default:
75 Q_UNREACHABLE();
76 }
77}
78//! [2]
bool listen(const QHostAddress &address, quint16 port)