QCA

ssltest.cpp

The code below shows how to create an SSL client

/*
Copyright (C) 2003-2005 Justin Karneges <[email protected]>
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)
{
switch (v) {
s = QStringLiteral("Validated");
break;
s = QStringLiteral("Root CA is marked to reject the specified purpose");
break;
s = QStringLiteral("Certificate not trusted for the required purpose");
break;
s = QStringLiteral("Invalid signature");
break;
s = QStringLiteral("Invalid CA certificate");
break;
s = QStringLiteral("Invalid certificate purpose");
break;
s = QStringLiteral("Certificate is self-signed");
break;
s = QStringLiteral("Certificate has been revoked");
break;
s = QStringLiteral("Maximum certificate chain length exceeded");
break;
s = QStringLiteral("Certificate has expired");
break;
s = QStringLiteral("CA has expired");
break;
default:
s = QStringLiteral("General certificate validation error");
break;
}
return s;
}
class SecureTest : public QObject
{
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);
}
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");
// We add this one to show how, and to make it work with
// the server example.
printf("Warning: no root certs\n");
else
ssl->setTrustedCertificates(rootCerts);
}
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)
{
sock_connectionClosed();
return;
}
printf("\nSocket error.\n");
emit quit();
}
void ssl_handshaken()
{
// We just do this to help doxygen...
QCA::TLS *ssl = SecureTest::ssl;
printf("Successful SSL handshake using %s (%i of %i bits)\n",
qPrintable(ssl->cipherSuite()),
ssl->cipherBits(),
ssl->cipherMaxBits());
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");
str += QStringLiteral("Error: Invalid certificate.\n -> Reason: ") +
validityToString(ssl->peerCertificateValidity());
else
str += QStringLiteral("Error: No certificate");
printf("%s\n", qPrintable(str));
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");
if (!issuerList.isEmpty()) {
printf("Allowed issuers:\n");
foreach (QCA::CertificateInfoOrdered i, issuerList)
printf(" %s\n", qPrintable(i.toString()));
}
}
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();
printf("SSL Handshake Error!\n");
emit quit();
} else {
printf("SSL Error!\n");
emit quit();
}
}
private:
QTcpSocket *sock;
QCA::TLS *ssl;
bool sock_done, ssl_done;
};
#include "ssltest.moc"
int main(int argc, char **argv)
{
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;
}
Q_OBJECTQ_OBJECT
IdentityResult
Type of identity.
QString toPEM() const
Export the Certificate into a PEM format.
int cipherMaxBits() const
The number of bits of security that the cipher could use.
@ ErrorExpiredCA
The Certificate Authority has expired.
Definition: qca_cert.h:509
void write(const QByteArray &a) override
This method writes unencrypted (plain) data to the SecureLayer implementation.
int toInt(bool *ok, int base) const const
@ ErrorInvalidPurpose
The purpose does not match the intended usage.
Definition: qca_cert.h:503
void readyRead()
This signal is emitted when SecureLayer has decrypted (application side) data ready to be read.
QCA_EXPORT CertificateCollection systemStore()
Get system-wide root Certificate Authority (CA) certificates.
Q_SLOTSQ_SLOTS
@ ErrorExpired
The certificate has expired, or is not yet valid (e.g.
Definition: qca_cert.h:507
Error errorCode() const
This method returns the type of error that has occurred.
@ ErrorPathLengthExceeded
The path length from the root CA to this certificate is too long.
Definition: qca_cert.h:506
void continueAfterStep()
Resumes TLS processing.
void setTrustedCertificates(const CertificateCollection &trusted)
Set up the set of trusted certificates that will be used to verify that the certificate provided is v...
QStringRef midRef(int position, int n) const const
QCA_EXPORT void init()
Initialise QCA.
QStringView mid(qsizetype start) const const
@ InvalidCertificate
invalid cert
static Certificate fromPEM(const QString &s, ConvertResult *result=nullptr, const QString &provider=QString())
Import the certificate from PEM format.
QByteArray toLatin1() const const
QMetaObject::Connection connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
QByteArray read() override
This method reads decrypted (plain) data from the SecureLayer implementation.
@ HostMismatch
valid cert provided, but wrong owner
int cipherBits() const
The number of effective bits of security being used for this connection.
QString commonName() const
The common name of the subject of the certificate.
@ ValidityGood
The certificate is valid.
Definition: qca_cert.h:498
void certificateRequested()
Emitted when the server requests a certificate.
Q_SCRIPTABLE Q_NOREPLY void start()
QList< CertificateInfoOrdered > issuerList() const
QString fromLocal8Bit(const char *str, int size)
void startClient(const QString &host=QString())
Start the TLS/SSL connection as a client.
QAction * quit(const QObject *recvr, const char *slot, QObject *parent)
void closed()
This signal is emitted when the SecureLayer connection is closed.
void writeIncoming(const QByteArray &a) override
This method accepts encoded (typically encrypted) data for processing.
@ ErrorRejected
The root CA rejected the certificate purpose.
Definition: qca_cert.h:499
QByteArray readOutgoing(int *plainBytes=nullptr) override
This method provides encoded (typically encrypted) data.
void readyRead()
@ ErrorHandshake
problem during the negotiation
@ ErrorInvalidCA
The Certificate Authority is invalid.
Definition: qca_cert.h:502
void errorOccurred(QAbstractSocket::SocketError socketError)
bool isEmpty() const const
QCA_EXPORT bool haveSystemStore()
Test if QCA can access the root CA certificates.
int indexOf(QChar ch, int from, Qt::CaseSensitivity cs) const const
CertificateChain peerCertificateChain() const
The CertificateChain from the peer (other end of the connection to the trusted root certificate).
@ ErrorSelfSigned
The certificate is self-signed, and is not found in the list of trusted certificates.
Definition: qca_cert.h:504
Q_SIGNALSQ_SIGNALS
ScriptableExtension * host() const
const Certificate & primary() const
Return the primary (end-user) Certificate.
Definition: qca_cert.h:1249
void readyReadOutgoing()
This signal is emitted when SecureLayer has encrypted (network side) data ready to be read.
QAbstractSocket::SocketError error() const const
QString fromLatin1(const char *str, int size)
QCA_EXPORT bool isSupported(const char *features, const QString &provider=QString())
Test if a capability (algorithm) is available.
@ ErrorRevoked
The certificate has been revoked.
Definition: qca_cert.h:505
Validity peerCertificateValidity() const
After the SSL/TLS handshake is valid, this method allows you to check if the received certificate fro...
@ ErrorValidityUnknown
Validity is unknown.
Definition: qca_cert.h:510
@ NoCertificate
identity unknown
IdentityResult peerIdentityResult() const
After the SSL/TLS handshake is complete, this method allows you to determine if the other end of the ...
QString cipherSuite() const
The cipher suite that has been negotiated for this connection.
QString toString(Qt::DateFormat format) const const
void error()
This signal is emitted when an error is detected.
@ Valid
identity is verified
Validity
The validity (or otherwise) of a certificate.
Definition: qca_cert.h:496
void handshaken()
Emitted when the protocol handshake is complete.
QString mid(int position, int n) const const
void addCertificate(const Certificate &cert)
Append a Certificate to this collection.
@ ErrorUntrusted
The certificate is not trusted.
Definition: qca_cert.h:500
@ ErrorSignatureFailed
The signature does not match.
Definition: qca_cert.h:501
char * data()
QDateTime notValidBefore() const
The earliest date that the certificate is valid.
QString toString() const
Convert to RFC 1779 string format.
Definition: qca_cert.h:577
QDateTime notValidAfter() const
The latest date that the certificate is valid.
This file is part of the KDE documentation.
Documentation copyright © 1996-2023 The KDE developers.
Generated on Sat Sep 30 2023 03:47:09 by doxygen 1.8.17 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.