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";
{
public:
enum
{
Idle,
Handshaking,
Active,
Closing
};
SecureServer(quint16 _port)
: port(_port)
{
mode = Idle;
}
~SecureServer() override
{
delete ssl;
delete server;
}
void start()
{
qDebug() << "Error loading cert!";
return;
}
qDebug() << "Error loading private key!";
QTimer::singleShot(0, this, &SecureServer::quit);
return;
}
qDebug() << "Error binding to port " << port;
QTimer::singleShot(0, this, &SecureServer::quit);
return;
}
qDebug() << "Listening on port" << port;
}
void quit();
void sock_readyRead()
{
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();
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
#else
connect(sock, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error), this, &SecureServer::sock_error);
#endif
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;
ssl->continueAfterStep();
}
void ssl_readyRead()
{
ssl->read();
QByteArray b =
"<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;
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::Certificate cert;
QCA::PrivateKey privkey;
bool sent;
int mode;
qint64 bytesLeft;
};
#include "sslservtest.moc"
int main(int argc, char **argv)
{
QCA::Initializer init;
QCoreApplication app(argc, argv);
qDebug() << "TLS not supported!";
return 1;
}
SecureServer *server = new SecureServer(port);
app.exec();
delete server;
return 0;
}
static Certificate fromPEM(const QString &s, ConvertResult *result=nullptr, const QString &provider=QString())
Import the certificate from PEM format.
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 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.
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.
QByteArray readOutgoing(int *plainBytes=nullptr) override
This method provides encoded (typically encrypted) data.
QByteArray read() override
This method reads decrypted (plain) data from the SecureLayer implementation.
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.
QCA_EXPORT bool isSupported(const char *features, const QString &provider=QString())
Test if a capability (algorithm) is available.
SocketError
virtual qint64 bytesAvailable() const const override
virtual void close() override
void disconnected()
SocketError error() const const
void errorOccurred(QAbstractSocket::SocketError socketError)
char * data()
void resize(qsizetype newSize, char c)
qsizetype size() const const
void quit()
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()
singleShot
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
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.