File: ssltest.cpp

package info (click to toggle)
qca2 2.3.10-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,884 kB
  • sloc: cpp: 59,224; ansic: 814; perl: 133; sh: 89; makefile: 34
file content (331 lines) | stat: -rw-r--r-- 10,379 bytes parent folder | download
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
/*
 Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <QtCrypto>

#include <QCoreApplication>
#include <QTcpSocket>

#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif

char exampleCA_cert[] =
    "-----BEGIN CERTIFICATE-----\n"
    "MIICSzCCAbSgAwIBAgIBADANBgkqhkiG9w0BAQUFADA4MRMwEQYDVQQDEwpFeGFt\n"
    "cGxlIENBMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRXhhbXBsZSBPcmcwHhcNMDYw\n"
    "MzE1MDY1ODMyWhcNMDYwNDE1MDY1ODMyWjA4MRMwEQYDVQQDEwpFeGFtcGxlIENB\n"
    "MQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRXhhbXBsZSBPcmcwgZ8wDQYJKoZIhvcN\n"
    "AQEBBQADgY0AMIGJAoGBAL6ULdOxmpeZ+G/ypV12eNO4qnHSVIPTrYPkQuweXqPy\n"
    "atwGFheG+hLVsNIh9GGOS0tCe7a3hBBKN0BJg1ppfk2x39cDx7hefYqjBuZvp/0O\n"
    "8Ja3qlQiJLezITZKLxMBrsibcvcuH8zpfUdys2yaN+YGeqNfjQuoNN3Byl1TwuGJ\n"
    "AgMBAAGjZTBjMB0GA1UdDgQWBBSQKCUCLNM7uKrAt5o7qv/yQm6qEzASBgNVHRMB\n"
    "Af8ECDAGAQEBAgEIMB4GA1UdEQQXMBWBE2V4YW1wbGVAZXhhbXBsZS5jb20wDgYD\n"
    "VR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBBQUAA4GBAAh+SIeT1Ao5qInw8oMSoTdO\n"
    "lQ6h67ec/Jk5KmK4OoskuimmHI0Sp0C5kOCLehXbsVWW8pXsNC2fv0d2HkdaSUcX\n"
    "hwLzqgyZXd4mupIYlaOTZhuHDwWPCAOZS4LVsi2tndTRHKCP12441JjNKhmZRhkR\n"
    "u5zzD60nWgM9dKTaxuZM\n"
    "-----END CERTIFICATE-----\n";

void showCertInfo(const QCA::Certificate &cert)
{
    printf("-- Cert --\n");
    printf(" CN: %s\n", qPrintable(cert.commonName()));
    printf(" Valid from: %s, until %s\n",
           qPrintable(cert.notValidBefore().toString()),
           qPrintable(cert.notValidAfter().toString()));
    printf(" PEM:\n%s\n", qPrintable(cert.toPEM()));
}

static QString validityToString(QCA::Validity v)
{
    QString s;
    switch (v) {
    case QCA::ValidityGood:
        s = QStringLiteral("Validated");
        break;
    case QCA::ErrorRejected:
        s = QStringLiteral("Root CA is marked to reject the specified purpose");
        break;
    case QCA::ErrorUntrusted:
        s = QStringLiteral("Certificate not trusted for the required purpose");
        break;
    case QCA::ErrorSignatureFailed:
        s = QStringLiteral("Invalid signature");
        break;
    case QCA::ErrorInvalidCA:
        s = QStringLiteral("Invalid CA certificate");
        break;
    case QCA::ErrorInvalidPurpose:
        s = QStringLiteral("Invalid certificate purpose");
        break;
    case QCA::ErrorSelfSigned:
        s = QStringLiteral("Certificate is self-signed");
        break;
    case QCA::ErrorRevoked:
        s = QStringLiteral("Certificate has been revoked");
        break;
    case QCA::ErrorPathLengthExceeded:
        s = QStringLiteral("Maximum certificate chain length exceeded");
        break;
    case QCA::ErrorExpired:
        s = QStringLiteral("Certificate has expired");
        break;
    case QCA::ErrorExpiredCA:
        s = QStringLiteral("CA has expired");
        break;
    case QCA::ErrorValidityUnknown:
    default:
        s = QStringLiteral("General certificate validation error");
        break;
    }
    return s;
}

class SecureTest : public QObject
{
    Q_OBJECT
public:
    SecureTest()
    {
        sock_done = false;
        ssl_done  = false;

        sock = new QTcpSocket;
        connect(sock, &QTcpSocket::connected, this, &SecureTest::sock_connected);
        connect(sock, &QTcpSocket::readyRead, this, &SecureTest::sock_readyRead);
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
        connect(sock, &QTcpSocket::errorOccurred, this, &SecureTest::sock_error);
#else
        connect(sock, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error), this, &SecureTest::sock_error);
#endif

        ssl = new QCA::TLS;
        connect(ssl, &QCA::TLS::certificateRequested, this, &SecureTest::ssl_certificateRequested);
        connect(ssl, &QCA::TLS::handshaken, this, &SecureTest::ssl_handshaken);
        connect(ssl, &QCA::TLS::readyRead, this, &SecureTest::ssl_readyRead);
        connect(ssl, &QCA::TLS::readyReadOutgoing, this, &SecureTest::ssl_readyReadOutgoing);
        connect(ssl, &QCA::TLS::closed, this, &SecureTest::ssl_closed);
        connect(ssl, &QCA::TLS::error, this, &SecureTest::ssl_error);
    }

    ~SecureTest() override
    {
        delete ssl;
        delete sock;
    }

    void start(const QString &_host)
    {
        int n = _host.indexOf(QLatin1Char(':'));
        int port;
        if (n != -1) {
            host = _host.mid(0, n);
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
            port = QStringView(_host).mid(n + 1).toInt();
#else
            port = _host.midRef(n + 1).toInt();
#endif
        } else {
            host = _host;
            port = 443;
        }

        printf("Trying %s:%d...\n", qPrintable(host), port);
        sock->connectToHost(host, port);
    }

Q_SIGNALS:
    void quit();

private Q_SLOTS:
    void sock_connected()
    {
        // We just do this to help doxygen...
        QCA::TLS *ssl = SecureTest::ssl;

        printf("Connected, starting TLS handshake...\n");

        QCA::CertificateCollection rootCerts = QCA::systemStore();

        // We add this one to show how, and to make it work with
        // the server example.
        rootCerts.addCertificate(QCA::Certificate::fromPEM(QString::fromLatin1(exampleCA_cert)));

        if (!QCA::haveSystemStore())
            printf("Warning: no root certs\n");
        else
            ssl->setTrustedCertificates(rootCerts);

        ssl->startClient(host);
    }

    void sock_readyRead()
    {
        // We just do this to help doxygen...
        QCA::TLS *ssl = SecureTest::ssl;

        ssl->writeIncoming(sock->readAll());
    }

    void sock_connectionClosed()
    {
        printf("\nConnection closed.\n");
        sock_done = true;

        if (ssl_done && sock_done)
            emit quit();
    }

    void sock_error(QAbstractSocket::SocketError x)
    {
        if (x == QAbstractSocket::RemoteHostClosedError) {
            sock_connectionClosed();
            return;
        }

        printf("\nSocket error.\n");
        emit quit();
    }

    void ssl_handshaken()
    {
        // We just do this to help doxygen...
        QCA::TLS *ssl = SecureTest::ssl;

        QCA::TLS::IdentityResult r = ssl->peerIdentityResult();

        printf("Successful SSL handshake using %s (%i of %i bits)\n",
               qPrintable(ssl->cipherSuite()),
               ssl->cipherBits(),
               ssl->cipherMaxBits());
        if (r != QCA::TLS::NoCertificate) {
            cert = ssl->peerCertificateChain().primary();
            if (!cert.isNull())
                showCertInfo(cert);
        }

        QString str = QStringLiteral("Peer Identity: ");
        if (r == QCA::TLS::Valid)
            str += QStringLiteral("Valid");
        else if (r == QCA::TLS::HostMismatch)
            str += QStringLiteral("Error: Wrong certificate");
        else if (r == QCA::TLS::InvalidCertificate)
            str += QStringLiteral("Error: Invalid certificate.\n -> Reason: ") +
                validityToString(ssl->peerCertificateValidity());
        else
            str += QStringLiteral("Error: No certificate");
        printf("%s\n", qPrintable(str));

        ssl->continueAfterStep();

        printf("Let's try a GET request now.\n");
        QString req = QStringLiteral("GET / HTTP/1.0\nHost: ") + host + QStringLiteral("\n\n");
        ssl->write(req.toLatin1());
    }

    void ssl_certificateRequested()
    {
        // We just do this to help doxygen...
        QCA::TLS *ssl = SecureTest::ssl;

        printf("Server requested client certificate.\n");
        QList<QCA::CertificateInfoOrdered> issuerList = ssl->issuerList();
        if (!issuerList.isEmpty()) {
            printf("Allowed issuers:\n");
            foreach (QCA::CertificateInfoOrdered i, issuerList)
                printf("  %s\n", qPrintable(i.toString()));
        }

        ssl->continueAfterStep();
    }

    void ssl_readyRead()
    {
        // We just do this to help doxygen...
        QCA::TLS *ssl = SecureTest::ssl;

        QByteArray a = ssl->read();
        printf("%s", a.data());
    }

    void ssl_readyReadOutgoing()
    {
        // We just do this to help doxygen...
        QCA::TLS *ssl = SecureTest::ssl;

        sock->write(ssl->readOutgoing());
    }

    void ssl_closed()
    {
        printf("SSL session closed.\n");
        ssl_done = true;

        if (ssl_done && sock_done)
            emit quit();
    }

    void ssl_error()
    {
        // We just do this to help doxygen...
        QCA::TLS *ssl = SecureTest::ssl;

        int x = ssl->errorCode();
        if (x == QCA::TLS::ErrorHandshake) {
            printf("SSL Handshake Error!\n");
            emit quit();
        } else {
            printf("SSL Error!\n");
            emit quit();
        }
    }

private:
    QString          host;
    QTcpSocket      *sock;
    QCA::TLS        *ssl;
    QCA::Certificate cert;
    bool             sock_done, ssl_done;
};

#include "ssltest.moc"

int main(int argc, char **argv)
{
    QCA::Initializer init;

    QCoreApplication app(argc, argv);
    QString          host = argc > 1 ? QString::fromLocal8Bit(argv[1]) : QStringLiteral("andbit.net");

    if (!QCA::isSupported("tls")) {
        printf("TLS not supported!\n");
        return 1;
    }

    SecureTest *s = new SecureTest;
    QObject::connect(s, &SecureTest::quit, &app, &QCoreApplication::quit);
    s->start(host);
    app.exec();
    delete s;

    return 0;
}