summaryrefslogtreecommitdiffstats
path: root/tests/auto/x509/tst_x509.cpp
blob: d00c3d9c7d197427058eaf24c27ba347bc4d3ea5 (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
/****************************************************************************
**
** Copyright (C) 2019 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt OPC UA module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtOpcUa/QOpcUaProvider>
#include <QtOpcUa/QOpcUaKeyPair>

#include <QtCore/QCoreApplication>
#include <QtCore/QScopedPointer>
#include <QOpcUaX509CertificateSigningRequest>
#include <QOpcUaX509ExtensionSubjectAlternativeName>
#include <QOpcUaX509ExtensionBasicConstraints>
#include <QOpcUaX509ExtensionKeyUsage>
#include <QOpcUaX509ExtensionExtendedKeyUsage>

#include <QtTest/QSignalSpy>
#include <QtTest/QtTest>

#define defineDataMethod(name) void name()\
{\
    QTest::addColumn<QString>("backend");\
    for (auto backend : m_backends) {\
        const QString rowName = QString("%1").arg(backend); \
        QTest::newRow(rowName.toLatin1().constData()) << backend ; \
    }\
}

class Tst_QOpcUaSecurity: public QObject
{
    Q_OBJECT

public:
    Tst_QOpcUaSecurity();

private slots:
    void initTestCase();
    void cleanupTestCase();

    defineDataMethod(keyPairs_data)
    void keyPairs();

    defineDataMethod(certificateSigningRequest_data)
    void certificateSigningRequest();

private:
    QStringList m_backends;
    QOpcUaProvider m_opcUa;
};

QByteArray textifyCertificateRequest(const QByteArray &data)
{
    QProcess p;
    p.start("openssl", QStringList {"req", "-text", "-noout"});
    p.waitForStarted();
    p.write(data);
    p.closeWriteChannel();
    p.waitForFinished();
    return p.readAllStandardOutput();
}

QByteArray textifyCertificate(const QByteArray &data)
{
    QProcess p;
    p.start("openssl", QStringList {"x509", "-text", "-noout"});
    p.waitForStarted();
    p.write(data);
    p.closeWriteChannel();
    p.waitForFinished();
    return p.readAllStandardOutput();
}

QByteArray asn1dump(const QByteArray &data)
{
    QProcess p;
    p.start("openssl", QStringList {"asn1parse", "-inform","PEM"});
    p.waitForStarted();
    p.write(data);
    p.closeWriteChannel();
    p.waitForFinished();
    return p.readAllStandardOutput();
}

Tst_QOpcUaSecurity::Tst_QOpcUaSecurity()
{
    m_backends = QOpcUaProvider::availableBackends();
}

void Tst_QOpcUaSecurity::initTestCase()
{
}

void Tst_QOpcUaSecurity::keyPairs()
{
    QFETCH(QString, backend);

    QOpcUaKeyPair key;
    QOpcUaKeyPair loadedKey;
    QByteArray byteArray;

    QVERIFY(key.hasPrivateKey() == false);

    // Generate key
    key.generateRsaKey(QOpcUaKeyPair::RsaKeyStrength::Bits1024);
    QVERIFY(key.hasPrivateKey() == true);

    // Export public key
    byteArray = key.publicKeyToByteArray();
    QVERIFY(byteArray.startsWith("-----BEGIN PUBLIC KEY-----\n"));
    QVERIFY(byteArray.endsWith("-----END PUBLIC KEY-----\n"));

    // Load public key
    QVERIFY(loadedKey.loadFromPemData(byteArray));
    QVERIFY(loadedKey.hasPrivateKey() == false);

    // Check unencrypted PEM export
    byteArray = key.privateKeyToByteArray(QOpcUaKeyPair::Cipher::Unencrypted, QString());
    QVERIFY(byteArray.startsWith("-----BEGIN PRIVATE KEY-----\n"));
    QVERIFY(byteArray.endsWith("-----END PRIVATE KEY-----\n"));

    // Load private key from PEM data
    QSignalSpy passwordSpy(&loadedKey, SIGNAL(passphraseNeeded(QString&,int,bool)));

    QVERIFY(loadedKey.loadFromPemData(byteArray));
    QVERIFY(loadedKey.hasPrivateKey() == true);
    QCOMPARE(passwordSpy.count(), 0);
    QCOMPARE(loadedKey.privateKeyToByteArray(QOpcUaKeyPair::Cipher::Unencrypted, QString()), byteArray);

    // Check encrypted PEM export
    byteArray = key.privateKeyToByteArray(QOpcUaKeyPair::Cipher::Aes128Cbc, QString("password"));
    QVERIFY(byteArray.startsWith("-----BEGIN ENCRYPTED PRIVATE KEY-----\n"));
    QVERIFY(byteArray.endsWith("-----END ENCRYPTED PRIVATE KEY-----\n"));
    QCOMPARE(passwordSpy.count(), 0);

    // Setup password callback
    QString passphraseToReturn;
    connect(&loadedKey, &QOpcUaKeyPair::passphraseNeeded, this, [&passphraseToReturn](QString &passphrase, int maximumLength, bool writeOperation){
        Q_UNUSED(maximumLength);
        qDebug() << "Requested a passphrase for" << (writeOperation ? "write":"read") << "operation";
        passphrase = passphraseToReturn;
    });

    // Load key with wrong password
    qDebug() << "Trying to decrypt with wrong password; will cause an error";
    passphraseToReturn = "WrongPassword";
    QVERIFY(!loadedKey.loadFromPemData(byteArray));
    QCOMPARE(passwordSpy.count(), 1);
    QVERIFY(loadedKey.hasPrivateKey() == false);

    // Load key with right password
    qDebug() << "Trying to decrypt with right password; will cause no error";
    passphraseToReturn = "password";
    QVERIFY(loadedKey.loadFromPemData(byteArray));
    QCOMPARE(passwordSpy.count(), 2);
    QCOMPARE(loadedKey.privateKeyToByteArray(QOpcUaKeyPair::Cipher::Unencrypted, QString()),
             key.privateKeyToByteArray(QOpcUaKeyPair::Cipher::Unencrypted, QString()));
    QVERIFY(loadedKey.hasPrivateKey() == true);
}

void Tst_QOpcUaSecurity::certificateSigningRequest()
{
    QFETCH(QString, backend);

    QOpcUaKeyPair key;

    // Generate key
    key.generateRsaKey(QOpcUaKeyPair::RsaKeyStrength::Bits1024);
    QVERIFY(key.hasPrivateKey() == true);

    QOpcUaX509CertificateSigningRequest csr;

    QOpcUaX509DistinguishedName dn;
    dn.setEntry(QOpcUaX509DistinguishedName::Type::CommonName, "QtOpcUaViewer");
    dn.setEntry(QOpcUaX509DistinguishedName::Type::CountryName, "DE");
    dn.setEntry(QOpcUaX509DistinguishedName::Type::LocalityName, "Berlin");
    dn.setEntry(QOpcUaX509DistinguishedName::Type::StateOrProvinceName, "Berlin");
    dn.setEntry(QOpcUaX509DistinguishedName::Type::OrganizationName, "The Qt Company");
    csr.setSubject(dn);

    QOpcUaX509ExtensionSubjectAlternativeName *san = new QOpcUaX509ExtensionSubjectAlternativeName;
    san->addEntry(QOpcUaX509ExtensionSubjectAlternativeName::Type::DNS, "foo.com");
    san->addEntry(QOpcUaX509ExtensionSubjectAlternativeName::Type::DNS, "bla.com");
    san->addEntry(QOpcUaX509ExtensionSubjectAlternativeName::Type::URI, "urn:foo.com:The%20Qt%20Company:QtOpcUaViewer");
    san->setCritical(true);
    csr.addExtension(san);

    QOpcUaX509ExtensionBasicConstraints *bc = new QOpcUaX509ExtensionBasicConstraints;
    bc->setCa(false);
    bc->setCritical(true);
    csr.addExtension(bc);

    QOpcUaX509ExtensionKeyUsage *ku = new QOpcUaX509ExtensionKeyUsage;
    ku->setCritical(true);
    ku->setKeyUsage(QOpcUaX509ExtensionKeyUsage::KeyUsage::DigitalSignature);
    ku->setKeyUsage(QOpcUaX509ExtensionKeyUsage::KeyUsage::NonRepudiation);
    ku->setKeyUsage(QOpcUaX509ExtensionKeyUsage::KeyUsage::KeyEncipherment);
    ku->setKeyUsage(QOpcUaX509ExtensionKeyUsage::KeyUsage::DataEncipherment);
    ku->setKeyUsage(QOpcUaX509ExtensionKeyUsage::KeyUsage::CertificateSigning);
    csr.addExtension(ku);

    QOpcUaX509ExtensionExtendedKeyUsage *eku = new QOpcUaX509ExtensionExtendedKeyUsage;
    eku->setCritical(true);
    eku->setKeyUsage(QOpcUaX509ExtensionExtendedKeyUsage::KeyUsage::EmailProtection);
    csr.addExtension(eku);

    QByteArray csrData = csr.createRequest(key);
    qDebug() << csrData;
    QVERIFY(csrData.startsWith("-----BEGIN CERTIFICATE REQUEST-----\n"));
    QVERIFY(csrData.endsWith("\n-----END CERTIFICATE REQUEST-----\n"));
    qDebug().noquote() << textifyCertificateRequest(csrData);
    qDebug().noquote() << asn1dump(csrData);

    QByteArray certData = csr.createSelfSignedCertificate(key);
    qDebug() << certData;
    QVERIFY(certData.startsWith("-----BEGIN CERTIFICATE-----\n"));
    QVERIFY(certData.endsWith("\n-----END CERTIFICATE-----\n"));
    qDebug().noquote() << textifyCertificate(certData);
    qDebug().noquote() << asn1dump(certData);
}

void Tst_QOpcUaSecurity::cleanupTestCase()
{
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QTEST_SET_MAIN_SOURCE_PATH

    // run tests for all available backends
    QStringList availableBackends = QOpcUaProvider::availableBackends();
    if (availableBackends.empty()) {
        qDebug("No OPCUA backends found, skipping tests.");
        return EXIT_SUCCESS;
    }

    Tst_QOpcUaSecurity tc;
    return QTest::qExec(&tc, argc, argv);
}

#include "tst_x509.moc"