QCA
saslserver.cpp
The code below shows how to create a SASL server.
The code below shows how to create a SASL server.
/*
Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
Copyright (C) 2006 Michail Pishchagin
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 <QCoreApplication>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTimer>
#include <cstdio>
// QtCrypto has the declarations for all of QCA
#include <QtCrypto>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
{
QString s;
switch (x) {
s = QStringLiteral("connection refused or timed out");
break;
s = QStringLiteral("remote host closed the connection");
break;
s = QStringLiteral("host not found");
break;
s = QStringLiteral("access error");
break;
s = QStringLiteral("too many sockets");
break;
s = QStringLiteral("operation timed out");
break;
s = QStringLiteral("datagram was larger than system limit");
break;
s = QStringLiteral("network error");
break;
s = QStringLiteral("address is already in use");
break;
s = QStringLiteral("address does not belong to the host");
break;
s = QStringLiteral("operation is not supported by the local operating system");
break;
default:
s = QStringLiteral("unknown socket error");
break;
}
return s;
}
{
QString s;
switch (x) {
s = QStringLiteral("no appropriate mechanism could be negotiated");
break;
s = QStringLiteral("bad SASL protocol");
break;
s = QStringLiteral("authentication failed");
break;
s = QStringLiteral("authorization failed");
break;
s = QStringLiteral("mechanism too weak for this user");
break;
s = QStringLiteral("encryption is needed to use this mechanism");
break;
s = QStringLiteral("passphrase expired");
break;
s = QStringLiteral("account is disabled");
break;
s = QStringLiteral("user not found");
break;
s = QStringLiteral("needed remote service is unavailable");
break;
// AuthFail or unknown (including those defined for client only)
default:
s = QStringLiteral("generic authentication failure");
break;
};
return s;
}
// --- ServerTest declaration
{
private:
QString host, proto, realm, str;
int port;
QTcpServer *tcpServer;
QList<int> ids;
public:
ServerTest(const QString &_host, int _port, const QString &_proto, const QString &_realm, const QString &_str);
int reserveId();
void releaseId(int id);
void start();
void quit();
private Q_SLOTS:
void server_newConnection();
};
// --- ServerTestHandler
{
private:
ServerTest *serverTest;
QTcpSocket *sock;
QCA::SASL *sasl;
int id;
QString host, proto, realm, str;
int mode; // 0 = receive mechanism list, 1 = sasl negotiation, 2 = app
int toWrite;
public:
ServerTestHandler(ServerTest *_serverTest,
QTcpSocket *_sock,
const QString &_host,
const QString &_proto,
const QString &_realm,
const QString &_str)
: serverTest(_serverTest)
, sock(_sock)
, host(_host)
, proto(_proto)
, realm(_realm)
, str(_str)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
#else
connect(sock,
QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error),
this,
&ServerTestHandler::sock_error);
#endif
mode = 0; // mech list mode
toWrite = 0;
int flags = 0;
flags |= QCA::SASL::AllowPlain;
flags |= QCA::SASL::AllowAnonymous;
printf("%d: Connection received! Starting SASL handshake...\n", id);
sasl->startServer(proto, host, realm);
}
~ServerTestHandler() override
{
}
private Q_SLOTS:
void sasl_serverStarted()
{
}
void sock_disconnected()
{
printf("%d: Connection closed.\n", id);
discard();
}
void sock_error(QAbstractSocket::SocketError x)
{
if (x == QAbstractSocket::RemoteHostClosedError) {
printf("%d: Error: client closed connection unexpectedly.\n", id);
discard();
return;
}
printf("%d: Error: socket: %s\n", id, qPrintable(socketErrorToString(x)));
discard();
}
void sock_readyRead()
{
handleLine(line);
}
}
void sock_bytesWritten(qint64 x)
{
if (mode == 2) // app mode
{
toWrite -= sasl->convertBytesWritten(x);
if (toWrite == 0) {
printf("%d: Sent, closing.\n", id);
sock->close();
}
}
}
{
QString line = QStringLiteral("C");
line += arrayToString(stepData);
}
sendLine(line);
}
{
printf("%d: AuthCheck: User: [%s], Authzid: [%s]\n", id, qPrintable(user), qPrintable(authzid));
// user - who has logged in, confirmed by sasl
// authzid - the identity the user wishes to act as, which
// could be another user or just any arbitrary string (in
// XMPP, this field holds a Jabber ID, for example). this
// field is not necessarily confirmed by sasl, and the
// decision about whether the user can act as the authzid
// must be made by the app.
// for this simple example program, we allow anyone to use
// the service, and simply continue onward with the
// negotiation.
sasl->continueAfterAuthCheck();
}
void sasl_authenticated()
{
sendLine(QStringLiteral("A"));
printf("%d: Authentication success.\n", id);
mode = 2; // switch to app mode
sendLine(str);
}
void sasl_readyRead()
{
}
void sasl_readyReadOutgoing()
{
}
void sasl_error()
{
printf("%d: Error: sasl: initialization failed.\n", id);
sendLine(QStringLiteral("E,") + errstr);
printf("%d: Error: sasl: %s.\n", id, qPrintable(errstr));
printf("%d: Error: sasl: broken security layer.\n", id);
} else {
printf("%d: Error: sasl: unknown error.\n", id);
}
sock->close();
}
private:
void discard()
{
deleteLater();
}
{
printf("%d: Reading: [%s]\n", id, qPrintable(line));
if (mode == 0) {
if (n != -1) {
sasl->putServerFirstStep(mech, stringToArray(rest));
} else
sasl->putServerFirstStep(line);
++mode;
} else if (mode == 1) {
if (n != -1) {
rest = line.mid(n + 1);
} else {
type = line;
}
sasl->putStep(stringToArray(rest));
} else {
printf("%d: Bad format from peer, closing.\n", id);
sock->close();
return;
}
}
}
{
QCA::Base64 encoder;
}
{
return decoder.stringToArray(s).toByteArray();
}
{
printf("%d: Writing: {%s}\n", id, qPrintable(line));
QByteArray a = s.toUtf8();
if (mode == 2) // app mode
{
toWrite += a.size();
} else // mech list or sasl negotiation
sock->write(a); // write to socket
}
};
// --- ServerTest implementation
ServerTest::ServerTest(const QString &_host,
int _port,
const QString &_proto,
const QString &_realm,
const QString &_str)
: host(_host)
, proto(_proto)
, realm(_realm)
, str(_str)
, port(_port)
{
}
int ServerTest::reserveId()
{
int n = 0;
++n;
ids += n;
return n;
}
void ServerTest::releaseId(int id)
{
}
void ServerTest::start()
{
printf("Error: unable to bind to port %d.\n", port);
emit quit();
return;
}
printf("Serving on %s:%d, for protocol %s ...\n", qPrintable(host), port, qPrintable(proto));
}
void ServerTest::server_newConnection()
{
new ServerTestHandler(this, sock, host, proto, realm, str);
}
// ---
void usage()
{
printf("usage: saslserver host (message)\n");
printf("options: --proto=x, --realm=x\n");
}
int main(int argc, char **argv)
{
QCoreApplication qapp(argc, argv);
QStringList args = qapp.arguments();
args.removeFirst();
// options
QString realm;
continue;
QString var, val;
if (at != -1) {
var = opt.mid(0, at);
val = opt.mid(at + 1);
} else
var = opt;
proto = val;
realm = val;
args.removeAt(n);
--n; // adjust position
}
if (args.count() < 1) {
usage();
return 0;
}
QString host;
int port = 8001; // default port
QString hostinput = args[0];
QString str = QStringLiteral("Hello, World");
if (args.count() >= 2)
str = args[1];
if (at != -1) {
host = hostinput.mid(0, at);
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 2)
#else
port = hostinput.midRef(at + 1).toInt();
#endif
} else
host = hostinput;
printf("Error: SASL support not found.\n");
return 1;
}
ServerTest server(host, port, proto, realm, str);
QTimer::singleShot(0, &server, &ServerTest::start);
qapp.exec();
return 0;
}
#include "saslserver.moc"
Simple Authentication and Security Layer protocol implementation.
Definition qca_securelayer.h:832
void startServer(const QString &service, const QString &host, const QString &realm, ServerSendMode mode=DisableServerSendLast)
Initialise the server side of the connection.
void putServerFirstStep(const QString &mech)
Process the first step in server mode (server)
void authCheck(const QString &user, const QString &authzid)
This signal is emitted when the server needs to perform the authentication check.
void write(const QByteArray &a) override
This method writes unencrypted (plain) data to the SecureLayer implementation.
int convertBytesWritten(qint64 encryptedBytes) override
Convert encrypted bytes written to plain text bytes written.
void setConstraints(AuthFlags f, SecurityLevel s=SL_None)
Specify connection constraints.
void nextStep(const QByteArray &stepData)
This signal is emitted when there is data required to be sent over the network to complete the next s...
void continueAfterAuthCheck()
Continue negotiation after auth ids have been checked (server)
@ NeedEncrypt
Encryption is needed in order to use mechanism (server side only)
Definition qca_securelayer.h:857
@ RemoteUnavailable
Remote service needed for auth is gone (server side only)
Definition qca_securelayer.h:861
void serverStarted()
This signal is emitted after the server has been successfully started.
QByteArray read() override
This method reads decrypted (plain) data from the SecureLayer implementation.
AuthCondition authCondition() const
Return the reason for authentication failure.
QByteArray readOutgoing(int *plainBytes=nullptr) override
This method provides encoded (typically encrypted) data.
void readyReadOutgoing()
This signal is emitted when SecureLayer has encrypted (network side) data ready to be read.
void readyRead()
This signal is emitted when SecureLayer has decrypted (application side) data ready to be read.
QString arrayToString(const MemoryRegion &a)
Process an array in the "forward" direction, returning a QString.
void init(KXmlGuiWindow *window, KGameDifficulty *difficulty=nullptr)
VehicleSection::Type type(QStringView coachNumber, QStringView coachClassification)
QCA_EXPORT bool isSupported(const char *features, const QString &provider=QString())
Test if a capability (algorithm) is available.
QCA_EXPORT void setAppName(const QString &name)
Set the application name that will be used by SASL server mode.
SocketError
virtual void close() override
void disconnected()
SocketError error() const const
void errorOccurred(QAbstractSocket::SocketError socketError)
bool isEmpty() const const
qsizetype size() const const
void quit()
void bytesWritten(qint64 bytes)
virtual bool canReadLine() const const
QByteArray readLine(qint64 maxSize)
void readyRead()
qint64 write(const QByteArray &data)
bool contains(const AT &value) const const
qsizetype count() const const
QList< T > mid(qsizetype pos, qsizetype length) const const
qsizetype removeAll(const AT &t)
void removeAt(qsizetype i)
void removeFirst()
Q_OBJECTQ_OBJECT
Q_SIGNALSQ_SIGNALS
Q_SLOTSQ_SLOTS
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
void deleteLater()
void setParent(QObject *parent)
QString fromLatin1(QByteArrayView str)
qsizetype indexOf(QChar ch, qsizetype from, Qt::CaseSensitivity cs) const const
qsizetype length() const const
QString mid(qsizetype position, qsizetype n) const const
int toInt(bool *ok, int base) const const
QByteArray toUtf8() const const
void truncate(qsizetype position)
QString join(QChar separator) const const
QStringView mid(qsizetype start, qsizetype length) const const
int toInt(bool *ok, int base) const const
bool listen(const QHostAddress &address, quint16 port)
void newConnection()
virtual QTcpSocket * nextPendingConnection()
QFuture< ArgsType< Signal > > connect(Sender *sender, Signal signal)
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.