summaryrefslogtreecommitdiffstats
path: root/tests/auto/network/ssl/qsslserver/tst_qsslserver.cpp
blob: 77a86ceac31c981e9e9ec03852c566e76fb62a10 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include <QTest>
#include <QDebug>
#include <QSignalSpy>
#include <QTimer>

#include <QtNetwork/QSslServer>
#include <QtNetwork/QSslKey>
#include "private/qtlsbackend_p.h"

class tst_QSslServer : public QObject
{
    Q_OBJECT

private slots:
    void initTestCase();
    void testOneSuccessfulConnection();
    void testSelfSignedCertificateRejectedByServer();
    void testSelfSignedCertificateRejectedByClient();
#if QT_CONFIG(openssl)
    void testHandshakeInterruptedOnError();
    void testPreSharedKeyAuthenticationRequired();
#endif
    void plaintextClient();
    void quietClient();
    void twoGoodAndManyBadClients();

private:
    QString testDataDir;
    bool isTestingOpenSsl = false;
    QSslConfiguration selfSignedClientQSslConfiguration();
    QSslConfiguration selfSignedServerQSslConfiguration();
    QSslConfiguration createQSslConfiguration(QString keyFileName, QString certificateFileName);
};

class SslServerSpy : public QObject
{
    Q_OBJECT

public:
    SslServerSpy(QSslConfiguration &configuration);

    QSslServer server;
    QSignalSpy sslErrorsSpy;
    QSignalSpy peerVerifyErrorSpy;
    QSignalSpy errorOccurredSpy;
    QSignalSpy pendingConnectionAvailableSpy;
    QSignalSpy preSharedKeyAuthenticationRequiredSpy;
    QSignalSpy alertSentSpy;
    QSignalSpy alertReceivedSpy;
    QSignalSpy handshakeInterruptedOnErrorSpy;
    QSignalSpy startedEncryptionHandshakeSpy;
};

SslServerSpy::SslServerSpy(QSslConfiguration &configuration)
    : server(),
      sslErrorsSpy(&server, &QSslServer::sslErrors),
      peerVerifyErrorSpy(&server, &QSslServer::peerVerifyError),
      errorOccurredSpy(&server, &QSslServer::errorOccurred),
      pendingConnectionAvailableSpy(&server, &QSslServer::pendingConnectionAvailable),
      preSharedKeyAuthenticationRequiredSpy(&server,
                                            &QSslServer::preSharedKeyAuthenticationRequired),
      alertSentSpy(&server, &QSslServer::alertSent),
      alertReceivedSpy(&server, &QSslServer::alertReceived),
      handshakeInterruptedOnErrorSpy(&server, &QSslServer::handshakeInterruptedOnError),
      startedEncryptionHandshakeSpy(&server, &QSslServer::startedEncryptionHandshake)
{
    server.setSslConfiguration(configuration);
}

void tst_QSslServer::initTestCase()
{
    testDataDir = QFileInfo(QFINDTESTDATA("certs")).absolutePath();
    if (testDataDir.isEmpty())
        testDataDir = QCoreApplication::applicationDirPath();
    if (!testDataDir.endsWith(QLatin1String("/")))
        testDataDir += QLatin1String("/");

    const QString openSslBackend = QTlsBackend::builtinBackendNames[QTlsBackend::nameIndexOpenSSL];
    const auto &tlsBackends = QSslSocket::availableBackends();
    if (tlsBackends.contains(openSslBackend)) {
        isTestingOpenSsl = true;
    }
}

QSslConfiguration tst_QSslServer::selfSignedClientQSslConfiguration()
{
    return createQSslConfiguration(testDataDir + "certs/selfsigned-client.key",
                                   testDataDir + "certs/selfsigned-client.crt");
}

QSslConfiguration tst_QSslServer::selfSignedServerQSslConfiguration()
{
    return createQSslConfiguration(testDataDir + "certs/selfsigned-server.key",
                                   testDataDir + "certs/selfsigned-server.crt");
}

QSslConfiguration tst_QSslServer::createQSslConfiguration(QString keyFileName,
                                                          QString certificateFileName)
{
    QSslConfiguration configuration(QSslConfiguration::defaultConfiguration());

    QFile keyFile(keyFileName);
    if (keyFile.open(QIODevice::ReadOnly)) {
        QSslKey key(keyFile.readAll(), QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey);
        if (!key.isNull()) {
            configuration.setPrivateKey(key);
        } else {
            qCritical() << "Could not parse key: " << keyFileName;
        }
    } else {
        qCritical() << "Could not find key: " << keyFileName;
    }

    QList<QSslCertificate> localCert = QSslCertificate::fromPath(certificateFileName);
    if (!localCert.isEmpty() && !localCert.first().isNull()) {
        configuration.setLocalCertificate(localCert.first());
    } else {
        qCritical() << "Could not find certificate: " << certificateFileName;
    }
    return configuration;
}

void tst_QSslServer::testOneSuccessfulConnection()
{
    // Setup server
    QSslConfiguration serverConfiguration = selfSignedServerQSslConfiguration();
    SslServerSpy server(serverConfiguration);
    QVERIFY(server.server.listen());

    // Check that all signal spys are valid
    QVERIFY(server.sslErrorsSpy.isValid());
    QVERIFY(server.peerVerifyErrorSpy.isValid());
    QVERIFY(server.errorOccurredSpy.isValid());
    QVERIFY(server.pendingConnectionAvailableSpy.isValid());
    QVERIFY(server.preSharedKeyAuthenticationRequiredSpy.isValid());
    QVERIFY(server.alertSentSpy.isValid());
    QVERIFY(server.alertReceivedSpy.isValid());
    QVERIFY(server.handshakeInterruptedOnErrorSpy.isValid());
    QVERIFY(server.startedEncryptionHandshakeSpy.isValid());

    // Check that no connections has occurred
    QCOMPARE(server.sslErrorsSpy.count(), 0);
    QCOMPARE(server.peerVerifyErrorSpy.count(), 0);
    QCOMPARE(server.errorOccurredSpy.count(), 0);
    QCOMPARE(server.pendingConnectionAvailableSpy.count(), 0);
    QCOMPARE(server.preSharedKeyAuthenticationRequiredSpy.count(), 0);
    QCOMPARE(server.alertSentSpy.count(), 0);
    QCOMPARE(server.alertReceivedSpy.count(), 0);
    QCOMPARE(server.handshakeInterruptedOnErrorSpy.count(), 0);
    QCOMPARE(server.startedEncryptionHandshakeSpy.count(), 0);

    // Connect client
    QSslSocket client;
    QSslConfiguration clientConfiguration = QSslConfiguration::defaultConfiguration();
    client.setSslConfiguration(clientConfiguration);
    client.connectToHostEncrypted(QHostAddress(QHostAddress::LocalHost).toString(),
                                  server.server.serverPort());

    // Type of certificate error to expect
    const auto certificateError =
            isTestingOpenSsl ? QSslError::SelfSignedCertificate : QSslError::CertificateUntrusted;
    // Expected errors
    connect(&client, &QSslSocket::sslErrors,
            [&certificateError, &client](const QList<QSslError> &errors) {
                QCOMPARE(errors.size(), 2);
                for (auto error : errors) {
                    QVERIFY(error.error() == certificateError
                            || error.error() == QSslError::HostNameMismatch);
                }
                client.ignoreSslErrors();
            });

    QEventLoop loop;
    int waitFor = 2;
    connect(&client, &QSslSocket::encrypted, [&loop, &waitFor]() {
        if (!--waitFor)
            loop.quit();
    });
    connect(&server.server, &QTcpServer::pendingConnectionAvailable, [&loop, &waitFor]() {
        if (!--waitFor)
            loop.quit();
    });
    QTimer::singleShot(5000, &loop, SLOT(quit()));
    loop.exec();

    // Check that one encrypted connection has occurred without error
    QCOMPARE(server.sslErrorsSpy.count(), 0);
    QCOMPARE(server.peerVerifyErrorSpy.count(), 0);
    QCOMPARE(server.errorOccurredSpy.count(), 0);
    QCOMPARE(server.pendingConnectionAvailableSpy.count(), 1);
    QCOMPARE(server.preSharedKeyAuthenticationRequiredSpy.count(), 0);
    QCOMPARE(server.alertSentSpy.count(), 0);
    QCOMPARE(server.alertReceivedSpy.count(), 0);
    QCOMPARE(server.handshakeInterruptedOnErrorSpy.count(), 0);
    QCOMPARE(server.startedEncryptionHandshakeSpy.count(), 1);

    // Check client socket
    QVERIFY(client.isEncrypted());
    QCOMPARE(client.state(), QAbstractSocket::ConnectedState);
}

void tst_QSslServer::testSelfSignedCertificateRejectedByServer()
{
    // Set up server that verifies client
    QSslConfiguration serverConfiguration = selfSignedServerQSslConfiguration();
    serverConfiguration.setPeerVerifyMode(QSslSocket::VerifyPeer);
    SslServerSpy server(serverConfiguration);
    QVERIFY(server.server.listen());

    // Connect client
    QSslSocket client;
    QSslConfiguration clientConfiguration = selfSignedClientQSslConfiguration();
    clientConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone);
    client.setSslConfiguration(clientConfiguration);
    client.connectToHostEncrypted(QHostAddress(QHostAddress::LocalHost).toString(),
                                  server.server.serverPort());

    QEventLoop loop;
    QObject::connect(&client, SIGNAL(disconnected()), &loop, SLOT(quit()));
    QTimer::singleShot(5000, &loop, SLOT(quit()));
    loop.exec();

    // Check that one encrypted connection has failed
    QCOMPARE(server.sslErrorsSpy.count(), 1);
    QCOMPARE(server.peerVerifyErrorSpy.count(), 1);
    QCOMPARE(server.errorOccurredSpy.count(), 1);
    QCOMPARE(server.pendingConnectionAvailableSpy.count(), 0);
    QCOMPARE(server.preSharedKeyAuthenticationRequiredSpy.count(), 0);
    QCOMPARE(server.alertSentSpy.count(),
             isTestingOpenSsl ? 1 : 0); // OpenSSL only signal
    QCOMPARE(server.alertReceivedSpy.count(), 0);
    QCOMPARE(server.handshakeInterruptedOnErrorSpy.count(), 0);
    QCOMPARE(server.startedEncryptionHandshakeSpy.count(), 1);

    // Type of certificate error to expect
    const auto certificateError =
            isTestingOpenSsl ? QSslError::SelfSignedCertificate : QSslError::CertificateUntrusted;

    // Check the sslErrorsSpy
    const auto sslErrorsSpyErrors =
            qvariant_cast<QList<QSslError>>(qAsConst(server.sslErrorsSpy).first()[1]);
    QCOMPARE(sslErrorsSpyErrors.size(), 1);
    QCOMPARE(sslErrorsSpyErrors.first().error(), certificateError);

    // Check the peerVerifyErrorSpy
    const auto peerVerifyErrorSpyError =
            qvariant_cast<QSslError>(qAsConst(server.peerVerifyErrorSpy).first()[1]);
    QCOMPARE(peerVerifyErrorSpyError.error(), certificateError);

    // Check client socket
    QVERIFY(!client.isEncrypted());
    QCOMPARE(client.state(), QAbstractSocket::UnconnectedState);
}

void tst_QSslServer::testSelfSignedCertificateRejectedByClient()
{
    // Set up server without verification of client
    QSslConfiguration serverConfiguration = selfSignedServerQSslConfiguration();
    SslServerSpy server(serverConfiguration);
    QVERIFY(server.server.listen());

    // Connect client that authenticates server
    QSslSocket client;
    QSslConfiguration clientConfiguration = selfSignedClientQSslConfiguration();
    if (isTestingOpenSsl) {
        clientConfiguration.setHandshakeMustInterruptOnError(true);
        QVERIFY(clientConfiguration.handshakeMustInterruptOnError());
    }
    client.setSslConfiguration(clientConfiguration);
    QSignalSpy clientConnectedSpy(&client, SIGNAL(connected()));
    QSignalSpy clientHostFoundSpy(&client, SIGNAL(hostFound()));
    QSignalSpy clientDisconnectedSpy(&client, SIGNAL(disconnected()));
    QSignalSpy clientConnectionEncryptedSpy(&client, SIGNAL(encrypted()));
    QSignalSpy clientSslErrorsSpy(&client, SIGNAL(sslErrors(QList<QSslError>)));
    QSignalSpy clientErrorOccurredSpy(&client, SIGNAL(errorOccurred(QAbstractSocket::SocketError)));
    client.connectToHostEncrypted(QHostAddress(QHostAddress::LocalHost).toString(),
                                  server.server.serverPort());
    QEventLoop loop;
    QTimer::singleShot(1000, &loop, SLOT(quit()));
    loop.exec();

    // Type of socket error to expect
    const auto socketError = isTestingOpenSsl
            ? QAbstractSocket::SocketError::SslHandshakeFailedError
            : QAbstractSocket::SocketError::RemoteHostClosedError;

    QTcpSocket *connection = server.server.nextPendingConnection();
    if (connection == nullptr) {
        // Client disconnected before connection accepted by server
        QCOMPARE(server.sslErrorsSpy.count(), 0);
        QCOMPARE(server.peerVerifyErrorSpy.count(), 0);
        QCOMPARE(server.errorOccurredSpy.count(), 1); // Client rejected first
        QCOMPARE(server.pendingConnectionAvailableSpy.count(), 0);
        QCOMPARE(server.preSharedKeyAuthenticationRequiredSpy.count(), 0);
        QCOMPARE(server.alertSentSpy.count(), 0);
        QCOMPARE(server.alertReceivedSpy.count(),
                 isTestingOpenSsl ? 1 : 0); // OpenSSL only signal
        QCOMPARE(server.handshakeInterruptedOnErrorSpy.count(), 0);
        QCOMPARE(server.startedEncryptionHandshakeSpy.count(), 1);

        const auto errrOccuredSpyError = qvariant_cast<QAbstractSocket::SocketError>(
                qAsConst(server.errorOccurredSpy).first()[1]);
        QCOMPARE(errrOccuredSpyError, socketError);
    } else {
        // Client disconnected after connection accepted by server
        QCOMPARE(server.sslErrorsSpy.count(), 0);
        QCOMPARE(server.peerVerifyErrorSpy.count(), 0);
        QCOMPARE(server.errorOccurredSpy.count(), 0); // Server accepted first
        QCOMPARE(server.pendingConnectionAvailableSpy.count(), 1);
        QCOMPARE(server.preSharedKeyAuthenticationRequiredSpy.count(), 0);
        QCOMPARE(server.alertSentSpy.count(), 0);
        QCOMPARE(server.alertReceivedSpy.count(),
                 isTestingOpenSsl ? 1 : 0); // OpenSSL only signal
        QCOMPARE(server.handshakeInterruptedOnErrorSpy.count(), 0);
        QCOMPARE(server.startedEncryptionHandshakeSpy.count(), 1);

        QCOMPARE(connection->state(), QAbstractSocket::UnconnectedState);
        QCOMPARE(connection->error(), socketError);
        auto sslConnection = qobject_cast<QSslSocket *>(connection);
        QVERIFY(sslConnection);
        QVERIFY(!sslConnection->isEncrypted());
    }

    // Check that client has rejected server
    QCOMPARE(clientConnectedSpy.count(), 1);
    QCOMPARE(clientHostFoundSpy.count(), 1);
    QCOMPARE(clientDisconnectedSpy.count(), 1);
    QCOMPARE(clientConnectionEncryptedSpy.count(), 0);
    QCOMPARE(clientSslErrorsSpy.count(), isTestingOpenSsl ? 0 : 1);
    QCOMPARE(clientErrorOccurredSpy.count(), 1);

    // Check client socket
    QVERIFY(!client.isEncrypted());
    QCOMPARE(client.state(), QAbstractSocket::UnconnectedState);
}

#if QT_CONFIG(openssl)

void tst_QSslServer::testHandshakeInterruptedOnError()
{
    if (!isTestingOpenSsl)
        QSKIP("This test requires OpenSSL as the active TLS backend");

    auto serverConfiguration = selfSignedServerQSslConfiguration();
    serverConfiguration.setHandshakeMustInterruptOnError(true);
    QVERIFY(serverConfiguration.handshakeMustInterruptOnError());
    serverConfiguration.setPeerVerifyMode(QSslSocket::VerifyPeer);
    SslServerSpy server(serverConfiguration);
    server.server.listen();

    QSslSocket client;
    auto clientConfiguration = selfSignedClientQSslConfiguration();
    clientConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone);
    client.setSslConfiguration(clientConfiguration);
    client.connectToHostEncrypted(QHostAddress(QHostAddress::LocalHost).toString(),
                                  server.server.serverPort());

    QEventLoop loop;
    QObject::connect(&client, SIGNAL(disconnected()), &loop, SLOT(quit()));
    QTimer::singleShot(5000, &loop, SLOT(quit()));
    loop.exec();

    // Check that client certificate causes handshake interrupted signal to be emitted
    QCOMPARE(server.sslErrorsSpy.count(), 0);
    QCOMPARE(server.peerVerifyErrorSpy.count(), 0);
    QCOMPARE(server.errorOccurredSpy.count(), 1);
    QCOMPARE(server.pendingConnectionAvailableSpy.count(), 0);
    QCOMPARE(server.preSharedKeyAuthenticationRequiredSpy.count(), 0);
    QCOMPARE(server.alertSentSpy.count(), 1);
    QCOMPARE(server.alertReceivedSpy.count(), 0);
    QCOMPARE(server.handshakeInterruptedOnErrorSpy.count(), 1);
    QCOMPARE(server.startedEncryptionHandshakeSpy.count(), 1);
}

void tst_QSslServer::testPreSharedKeyAuthenticationRequired()
{
    if (!isTestingOpenSsl)
        QSKIP("This test requires OpenSSL as the active TLS backend");

    auto serverConfiguration = QSslConfiguration::defaultConfiguration();
    serverConfiguration.setPeerVerifyMode(QSslSocket::VerifyPeer);
    serverConfiguration.setProtocol(QSsl::TlsV1_2);
    serverConfiguration.setCiphers({ QSslCipher("PSK-AES256-CBC-SHA") });
    serverConfiguration.setPreSharedKeyIdentityHint("Server Y");
    SslServerSpy server(serverConfiguration);
    connect(&server.server, &QSslServer::preSharedKeyAuthenticationRequired,
            [](QSslSocket *, QSslPreSharedKeyAuthenticator *authenticator) {
                QCOMPARE(authenticator->identity(), QByteArray("Client X"));
                authenticator->setPreSharedKey("123456");
            });
    server.server.listen();

    QSslSocket client;
    auto clientConfiguration = QSslConfiguration::defaultConfiguration();
    clientConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone);
    clientConfiguration.setProtocol(QSsl::TlsV1_2);
    clientConfiguration.setCiphers({ QSslCipher("PSK-AES256-CBC-SHA") });
    client.setSslConfiguration(clientConfiguration);
    connect(&client, &QSslSocket::preSharedKeyAuthenticationRequired,
            [](QSslPreSharedKeyAuthenticator *authenticator) {
                QCOMPARE(authenticator->identityHint(), QByteArray("Server Y"));
                authenticator->setPreSharedKey("123456");
                authenticator->setIdentity("Client X");
            });
    client.connectToHostEncrypted(QHostAddress(QHostAddress::LocalHost).toString(),
                                  server.server.serverPort());

    connect(&server.server, &QSslServer::sslErrors,
            [](QSslSocket *socket, const QList<QSslError> &errors) {
                for (auto error : errors) {
                    QCOMPARE(error.error(), QSslError::NoPeerCertificate);
                }
                socket->ignoreSslErrors();
            });

    QEventLoop loop;
    QObject::connect(&client, SIGNAL(encrypted()), &loop, SLOT(quit()));
    QTimer::singleShot(5000, &loop, SLOT(quit()));
    loop.exec();

    // Check that server is connected
    QCOMPARE(server.sslErrorsSpy.count(), 1);
    QCOMPARE(server.peerVerifyErrorSpy.count(), 1);
    QCOMPARE(server.errorOccurredSpy.count(), 0);
    QCOMPARE(server.pendingConnectionAvailableSpy.count(), 1);
    QCOMPARE(server.preSharedKeyAuthenticationRequiredSpy.count(), 1);
    QCOMPARE(server.alertSentSpy.count(), 0);
    QCOMPARE(server.alertReceivedSpy.count(), 0);
    QCOMPARE(server.handshakeInterruptedOnErrorSpy.count(), 0);
    QCOMPARE(server.startedEncryptionHandshakeSpy.count(), 1);

    // Check client socket
    QVERIFY(client.isEncrypted());
    QCOMPARE(client.state(), QAbstractSocket::ConnectedState);
}

#endif

void tst_QSslServer::plaintextClient()
{
    QSslConfiguration serverConfiguration = selfSignedServerQSslConfiguration();
    SslServerSpy server(serverConfiguration);
    QVERIFY(server.server.listen());

    QTcpSocket socket;
    QSignalSpy socketDisconnectedSpy(&socket, &QTcpSocket::disconnected);
    socket.connectToHost(QHostAddress::LocalHost, server.server.serverPort());
    QVERIFY(socket.waitForConnected());
    QTest::qWait(100);
    // No disconnect from short break...:
    QCOMPARE(socket.state(), QAbstractSocket::SocketState::ConnectedState);

    // ... but we write some plaintext data...:
    socket.write("Hello World!");
    socket.waitForBytesWritten();
    // ... and quickly get disconnected:
    QTRY_COMPARE_GT(socketDisconnectedSpy.count(), 0);
    QCOMPARE(socket.state(), QAbstractSocket::SocketState::UnconnectedState);
}

void tst_QSslServer::quietClient()
{
    QSslConfiguration serverConfiguration = selfSignedServerQSslConfiguration();
    SslServerSpy server(serverConfiguration);
    server.server.setHandshakeTimeout(1'000);
    QVERIFY(server.server.listen());

    quint16 serverPeerPort = 0;
    auto grabServerPeerPort = [&serverPeerPort](QSslSocket *socket) {
        serverPeerPort = socket->peerPort();
    };
    QObject::connect(&server.server, &QSslServer::errorOccurred, &server.server,
                     grabServerPeerPort);

    QTcpSocket socket;
    QSignalSpy socketDisconnectedSpy(&socket, &QTcpSocket::disconnected);
    socket.connectToHost(QHostAddress::LocalHost, server.server.serverPort());
    quint16 clientLocalPort = socket.localPort();
    QVERIFY(socket.waitForConnected());
    // Disconnects after overlong break:
    QVERIFY(socketDisconnectedSpy.wait(5'000));
    QCOMPARE(socket.state(), QAbstractSocket::SocketState::UnconnectedState);

    QCOMPARE_GT(server.errorOccurredSpy.size(), 0);
    QCOMPARE(serverPeerPort, clientLocalPort);
}

void tst_QSslServer::twoGoodAndManyBadClients()
{
    QSslConfiguration serverConfiguration = selfSignedServerQSslConfiguration();
    SslServerSpy server(serverConfiguration);
    server.server.setHandshakeTimeout(750);
    constexpr qsizetype ExpectedConnections = 5;
    server.server.setMaxPendingConnections(ExpectedConnections);
    QVERIFY(server.server.listen());

    auto connectGoodClient = [&server](QSslSocket *socket) {
        QObject::connect(socket, &QSslSocket::sslErrors, socket,
                         qOverload<const QList<QSslError> &>(&QSslSocket::ignoreSslErrors));
        socket->connectToHostEncrypted("127.0.0.1", server.server.serverPort());
    };
    // Connect one socket encrypted so we have a socket in the regular queue
    QSslSocket tlsSocket;
    connectGoodClient(&tlsSocket);

    // Then we connect a bunch of TCP sockets who will not send any data at all
    std::array<QTcpSocket, size_t(ExpectedConnections) * 2> sockets;
    for (QTcpSocket &socket : sockets)
        socket.connectToHost(QHostAddress::LocalHost, server.server.serverPort());
    QTest::qWait(500); // some leeway to let connections try to connect...

    // I happen to know the sockets are all children of the server, so let's see
    // how many are created:
    qsizetype connectedCount = server.server.findChildren<QSslSocket *>().size();
    QCOMPARE(connectedCount, ExpectedConnections);
    // 1 socket is ready and pending
    QCOMPARE(server.pendingConnectionAvailableSpy.size(), 1);

    // Connect another client to make sure that the server is accepting connections again even after
    // all the bad actors tried to connect:
    QSslSocket goodClient;
    connectGoodClient(&goodClient);
    QTRY_COMPARE(server.pendingConnectionAvailableSpy.size(), 2);
}

QTEST_MAIN(tst_QSslServer)

#include "tst_qsslserver.moc"