QCA

sslservtest.cpp

The code below shows how to create an SSL server.

The code below shows how to create an SSL server.Note that this server returns a self-signed certificate for "example.com", and that the certificate is expired.

The design used here only allows for one connection at a time. If you want to allow for more, you should probably create a "TlsConnection" object that agregates a QCA::TLS object and a QTcpSocket (plus a little bit of state information) that handles a single connection. Then just create a TlsConnection for each server connection.

/*
Copyright (C) 2003 Justin Karneges <justin@affinix.com>
Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>
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 <QDebug>
#include <QHostAddress>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTimer>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
char pemdata_cert[] =
"-----BEGIN CERTIFICATE-----\n"
"MIICeTCCAeKgAwIBAgIRAKKKnOj6Aarmwf0phApitVAwDQYJKoZIhvcNAQEFBQAw\n"
"ODELMAkGA1UEBhMCVVMxFDASBgNVBAoTC0V4YW1wbGUgT3JnMRMwEQYDVQQDEwpF\n"
"eGFtcGxlIENBMB4XDTA2MDMxNTA3MDU1MloXDTA3MDMx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n"
"PcOEryY+gdFJE8DFgUD4f1huFsj4iCuNg+PaG42p+hf9IARNvSho/RcEaVg4AJrV\n"
"jRP8r7fSqcIGr6lGuvDFFv3SU5ddy84g5oqLYGKvuPSHMGfVsZSxAwOrzD4bH19L\n"
"SNqtNcpdBsBd7ZiEE4ECQQD/oJGui9D5Dx3QVcS+QV4F8wuyN9jYIANmX/17o0fl\n"
"BL0bwRU4RICwadrcybi5N0JQLIYSUm2HGqNvAJbtnuQxAkEA+WeYLLYPeawcy+WU\n"
"kGcOR7BUjHiG71+6cvU4XIDW2bezA04fqWXkZRFAwHTMpQb785/XalFftgS21kql\n"
"8yLDSwJAHkeT2hwftdDPlEUEmBDAJW5DvWmWGwu3u2G1cfbGZl9oUyhM7ixXHg57\n"
"6VlPs0jTZxHPE86FwNIr99MXDbCbkQJBAMDFOJK+ecGirXNP1P+0GA6DFSap9inJ\n"
"BRTbwx+EmgwX966DUOefEOSpbDIVVSPs/Qr2LgtIMEFA7Y0+j3wZD3cCQBsTwccd\n"
"ASQx59xakpq11eOlTYz14rjwodr4QMyj26WxEPJtz7hKokx/+EH6fWuPIUSrROM5\n"
"07y2gaVbYxtis0s=\n"
"-----END PRIVATE KEY-----\n";
class SecureServer : public QObject
{
public:
enum
{
Idle,
Handshaking,
Active,
Closing
};
SecureServer(quint16 _port)
: port(_port)
{
server = new QTcpServer;
connect(server, &QTcpServer::newConnection, this, &SecureServer::server_handleConnection);
ssl = new QCA::TLS;
connect(ssl, &QCA::TLS::handshaken, this, &SecureServer::ssl_handshaken);
connect(ssl, &QCA::TLS::readyRead, this, &SecureServer::ssl_readyRead);
connect(ssl, &QCA::TLS::readyReadOutgoing, this, &SecureServer::ssl_readyReadOutgoing);
connect(ssl, &QCA::TLS::closed, this, &SecureServer::ssl_closed);
connect(ssl, &QCA::TLS::error, this, &SecureServer::ssl_error);
privkey = QCA::PrivateKey::fromPEM(QString::fromLatin1(pemdata_privkey));
mode = Idle;
}
~SecureServer() override
{
delete ssl;
delete server;
}
void start()
{
if (cert.isNull()) {
qDebug() << "Error loading cert!";
QTimer::singleShot(0, this, &SecureServer::quit);
return;
}
if (privkey.isNull()) {
qDebug() << "Error loading private key!";
QTimer::singleShot(0, this, &SecureServer::quit);
return;
}
if (false == server->listen(QHostAddress::Any, port)) {
qDebug() << "Error binding to port " << port;
QTimer::singleShot(0, this, &SecureServer::quit);
return;
}
qDebug() << "Listening on port" << port;
}
void quit();
private Q_SLOTS:
void sock_readyRead()
{
QByteArray buf(sock->bytesAvailable(), 0x00);
int num = sock->read(buf.data(), buf.size());
if (-1 == num)
qDebug() << "Error reading data from socket";
if (num < buf.size())
buf.resize(num);
ssl->writeIncoming(buf);
}
void server_handleConnection()
{
// Note: only 1 connection supported at a time in this example!
if (mode != Idle) {
tmp->close();
qDebug() << "throwing away extra connection";
return;
}
mode = Handshaking;
sock = server->nextPendingConnection();
connect(sock, &QTcpSocket::readyRead, this, &SecureServer::sock_readyRead);
connect(sock, &QTcpSocket::disconnected, this, &SecureServer::sock_disconnected);
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
connect(sock, &QTcpSocket::errorOccurred, this, &SecureServer::sock_error);
#else
connect(sock, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error), this, &SecureServer::sock_error);
#endif
connect(sock, &QTcpSocket::bytesWritten, this, &SecureServer::sock_bytesWritten);
qDebug() << "Connection received! Starting TLS handshake.";
ssl->setCertificate(cert, privkey);
ssl->startServer();
}
void sock_disconnected()
{
qDebug() << "Connection closed.";
}
void sock_bytesWritten(qint64 x)
{
if (mode == Active && sent) {
qint64 bytes = ssl->convertBytesWritten(x);
bytesLeft -= bytes;
if (bytesLeft == 0) {
mode = Closing;
qDebug() << "Data transfer complete - SSL shutting down";
ssl->close();
}
}
}
void sock_error(QAbstractSocket::SocketError error)
{
qDebug() << "Socket error: " << (unsigned)error;
}
void ssl_handshaken()
{
qDebug() << "Successful SSL handshake. Waiting for newline.";
bytesLeft = 0;
sent = false;
mode = Active;
}
void ssl_readyRead()
{
ssl->read();
"<html>\n"
"<head><title>Test</title></head>\n"
"<body>this is only a test</body>\n"
"</html>\n";
qDebug() << "Sending test response.";
sent = true;
ssl->write(b);
}
void ssl_readyReadOutgoing()
{
int plainBytes;
QByteArray outgoingData = ssl->readOutgoing(&plainBytes);
sock->write(outgoingData);
}
void ssl_closed()
{
qDebug() << "Closing socket.";
sock->close();
mode = Idle;
}
void ssl_error()
{
qDebug() << "SSL Handshake Error! Closing.";
sock->close();
} else {
qDebug() << "SSL Error! Closing.";
sock->close();
}
mode = Idle;
}
private:
quint16 port;
QTcpServer *server;
QTcpSocket *sock;
QCA::TLS *ssl;
QCA::PrivateKey privkey;
bool sent;
int mode;
qint64 bytesLeft;
};
#include "sslservtest.moc"
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
int port = argc > 1 ? QString::fromLatin1(argv[1]).toInt() : 8000;
if (!QCA::isSupported("tls")) {
qDebug() << "TLS not supported!";
return 1;
}
SecureServer *server = new SecureServer(port);
QObject::connect(server, &SecureServer::quit, &app, &QCoreApplication::quit);
server->start();
app.exec();
delete server;
return 0;
}
Public Key (X.509) certificate.
Definition qca_cert.h:857
static Certificate fromPEM(const QString &s, ConvertResult *result=nullptr, const QString &provider=QString())
Import the certificate from PEM format.
bool isNull() const
Test if the certificate is empty (null)
Convenience method for initialising and cleaning up QCA.
Definition qca_core.h:660
bool isNull() const
Test if the key is null (empty)
Generic private key.
static PrivateKey fromPEM(const QString &s, const SecureArray &passphrase=SecureArray(), ConvertResult *result=nullptr, const QString &provider=QString())
Import the key from Privacy Enhanced Mail (PEM) format.
void error()
This signal is emitted when an error is detected.
void readyReadOutgoing()
This signal is emitted when SecureLayer has encrypted (network side) data ready to be read.
void closed()
This signal is emitted when the SecureLayer connection is closed.
void readyRead()
This signal is emitted when SecureLayer has decrypted (application side) data ready to be read.
Transport Layer Security / Secure Socket Layer.
void write(const QByteArray &a) override
This method writes unencrypted (plain) data to the SecureLayer implementation.
void writeIncoming(const QByteArray &a) override
This method accepts encoded (typically encrypted) data for processing.
void continueAfterStep()
Resumes TLS processing.
@ ErrorHandshake
problem during the negotiation
void startServer()
Start the TLS/SSL connection as a server.
QByteArray readOutgoing(int *plainBytes=nullptr) override
This method provides encoded (typically encrypted) data.
void close() override
Close the link.
QByteArray read() override
This method reads decrypted (plain) data from the SecureLayer implementation.
Error errorCode() const
This method returns the type of error that has occurred.
int convertBytesWritten(qint64 encryptedBytes) override
Convert encrypted bytes written to plain text bytes written.
void setCertificate(const CertificateChain &cert, const PrivateKey &key)
The local certificate to use.
void handshaken()
Emitted when the protocol handshake is complete.
QCA_EXPORT bool isSupported(const char *features, const QString &provider=QString())
Test if a capability (algorithm) is available.
virtual qint64 bytesAvailable() const const override
virtual void close() override
SocketError error() const const
void errorOccurred(QAbstractSocket::SocketError socketError)
char * data()
void resize(qsizetype newSize, char c)
qsizetype size() const const
void bytesWritten(qint64 bytes)
QByteArray read(qint64 maxSize)
void readyRead()
qint64 write(const QByteArray &data)
Q_OBJECTQ_OBJECT
Q_SIGNALSQ_SIGNALS
Q_SLOTSQ_SLOTS
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
void deleteLater()
QString fromLatin1(QByteArrayView str)
int toInt(bool *ok, int base) const const
bool listen(const QHostAddress &address, quint16 port)
void newConnection()
virtual QTcpSocket * nextPendingConnection()
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Fri Nov 8 2024 11:53:13 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.