QCA
saslclient.cpp
The code below shows how to create a SASL client.
The code below shows how to create a SASL client.
/*
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
{
printf("* %s ", qPrintable(s));
fflush(stdout);
char line[256];
fgets(line, 255, stdin);
return result;
}
{
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("server failed mutual authentication");
break;
// AuthFail or unknown (including those defined for server only)
default:
s = QStringLiteral("generic authentication failure");
break;
};
return s;
}
{
private:
QString host, proto, authzid, realm, user, pass;
int port;
bool no_authzid, no_realm;
int mode; // 0 = receive mechanism list, 1 = sasl negotiation, 2 = app
QTcpSocket *sock;
QCA::SASL *sasl;
QByteArray inbuf;
bool sock_done;
int waitCycles;
public:
ClientTest(const QString &_host,
int _port,
const QString &_proto,
const QString &_authzid,
const QString &_realm,
const QString &_user,
const QString &_pass,
bool _no_authzid,
bool _no_realm)
: host(_host)
, proto(_proto)
, authzid(_authzid)
, realm(_realm)
, user(_user)
, pass(_pass)
, port(_port)
, no_authzid(_no_authzid)
, no_realm(_no_realm)
, sock_done(false)
, waitCycles(0)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
#else
connect(sock, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error), this, &ClientTest::sock_error);
#endif
}
void start()
{
mode = 0; // mech list mode
int flags = 0;
flags |= QCA::SASL::AllowPlain;
flags |= QCA::SASL::AllowAnonymous;
sasl->setUsername(user);
if (!authzid.isEmpty())
sasl->setAuthzid(authzid);
if (!pass.isEmpty())
if (!realm.isEmpty())
sasl->setRealm(realm);
printf("Connecting to %s:%d, for protocol %s\n", qPrintable(host), port, qPrintable(proto));
sock->connectToHost(host, port);
}
void quit();
private Q_SLOTS:
void sock_connected()
{
printf("Connected to server. Awaiting mechanism list...\n");
}
void sock_error(QAbstractSocket::SocketError x)
{
if (x == QAbstractSocket::RemoteHostClosedError) {
if (mode == 2) // app mode, where disconnect means completion
{
sock_done = true;
tryFinished();
return;
} else // any other mode, where disconnect is an error
{
printf("Error: server closed connection unexpectedly.\n");
emit quit();
return;
}
}
printf("Error: socket: %s\n", qPrintable(socketErrorToString(x)));
emit quit();
}
void sock_readyRead()
{
if (mode == 2) // app mode
{
// there is a possible flaw in the qca 2.0 api, in
// that if sasl data is received from the peer
// followed by a disconnect from the peer, there is
// no clear approach to salvaging the bytes. tls is
// not affected because tls has the concept of
// closing a session. with sasl, there is no
// closing, and since the qca api is asynchronous,
// we could potentially wait forever for decoded
// data, if the last write was a partial packet.
//
// for now, we can perform a simple workaround of
// waiting at least three event loop cycles for
// decoded data before giving up and assuming the
// last write was partial. the fact is, all current
// qca sasl providers respond within this time
// frame, so this fix should work fine for now. in
// qca 2.1, we should revise the api to handle this
// situation better.
//
// further note: i guess this only affects application
// protocols that have no close message of their
// own, and rely on the tcp-level close. examples
// are http, and of course this qcatest protocol.
if (waitCycles == 0) {
waitCycles = 3;
}
sasl->writeIncoming(a);
} else // mech list or sasl negotiation mode
{
handleLine(line);
}
}
}
{
if (clientInit) {
line += QLatin1Char(' ');
line += arrayToString(clientInitData);
}
sendLine(line);
}
{
QString line = QStringLiteral("C");
line += QLatin1Char(',');
line += arrayToString(stepData);
}
sendLine(line);
}
{
user = prompt(QStringLiteral("Username:"));
sasl->setUsername(user);
}
authzid = prompt(QStringLiteral("Authorize As (enter to skip):"));
if (!authzid.isEmpty())
sasl->setAuthzid(authzid);
}
QCA::ConsolePrompt prompt;
prompt.waitForFinished();
sasl->setPassword(pass);
}
printf("Available realms:\n");
printf(" (none specified)\n");
printf(" %s\n", qPrintable(s));
realm = prompt(QStringLiteral("Realm (enter to skip):"));
if (!realm.isEmpty())
sasl->setRealm(realm);
}
sasl->continueAfterParams();
}
void sasl_authenticated()
{
printf("SASL success!\n");
}
void sasl_readyRead()
{
inbuf += a;
processInbuf();
}
void sasl_readyReadOutgoing()
{
sock->write(a);
}
void sasl_error()
{
printf("Error: sasl: initialization failed.\n");
printf("Error: sasl: broken security layer.\n");
else
printf("Error: sasl: unknown error.\n");
emit quit();
}
void waitWriteIncoming()
{
--waitCycles;
if (waitCycles > 0) {
return;
}
tryFinished();
}
private:
void tryFinished()
{
if (sock_done && waitCycles == 0) {
printf("Finished, server closed connection.\n");
// if we give up on waiting for a response to
// writeIncoming, then it might come late. in
// theory this shouldn't happen if we wait enough
// cycles, but if one were to arrive then it could
// occur between the request to quit the app and
// the actual quit of the app. to assist with
// debugging, then, we'll explicitly stop listening
// for signals here. otherwise the response may
// still be received and displayed, giving a false
// sense of correctness.
emit quit();
}
}
{
}
{
}
{
printf("Writing: {%s}\n", qPrintable(line));
QByteArray a = s.toUtf8();
if (mode == 2) // app mode
else // mech list or sasl negotiation
sock->write(a); // write to socket
}
void processInbuf()
{
// collect completed lines from inbuf
int at;
inbuf = inbuf.mid(at + 1);
}
// process the lines
handleLine(line);
}
{
printf("Reading: [%s]\n", qPrintable(line));
if (mode == 0) {
// first line is the method list
mode = 1; // switch to sasl negotiation mode
sasl->startClient(proto, host, mechlist);
} else if (mode == 1) {
if (n != -1) {
rest = line.mid(n + 1);
} else
type = line;
sasl->putStep(stringToArray(rest));
if (!rest.isEmpty())
printf("Error: server says: %s.\n", qPrintable(rest));
else
printf("Error: server error, unspecified.\n");
emit quit();
return;
printf("Authentication success.\n");
mode = 2; // switch to app mode
// at this point, the server may send us text
// lines for us to display and then close.
sock_readyRead(); // any extra data?
return;
} else {
printf("Error: Bad format from peer, closing.\n");
emit quit();
return;
}
}
}
};
void usage()
{
printf("usage: saslclient (options) host(:port) (user) (pass)\n");
printf("options: --proto=x, --authzid=x, --realm=x\n");
}
int main(int argc, char **argv)
{
QCoreApplication qapp(argc, argv);
QStringList args = qapp.arguments();
args.removeFirst();
// options
QString authzid, realm;
bool no_authzid = false;
bool no_realm = false;
continue;
QString var, val;
if (at != -1) {
var = opt.mid(0, at);
val = opt.mid(at + 1);
} else
var = opt;
proto = val;
// specifying empty authzid means force unspecified
if (val.isEmpty())
no_authzid = true;
else
authzid = val;
// specifying empty realm means force unspecified
if (val.isEmpty())
no_realm = true;
else
realm = val;
}
args.removeAt(n);
--n; // adjust position
}
if (args.count() < 1) {
usage();
return 0;
}
QString host, user, pass;
int port = 8001; // default port
QString hostinput = args[0];
if (args.count() >= 2)
user = args[1];
if (args.count() >= 3)
pass = args[2];
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;
}
ClientTest client(host, port, proto, authzid, realm, user, pass, no_authzid, no_realm);
QTimer::singleShot(0, &client, &ClientTest::start);
qapp.exec();
return 0;
}
#include "saslclient.moc"
void getHidden(const QString &promptStr)
Allow the user to enter data without it being echo'd to the terminal.
QByteArray toByteArray() const
Convert this memory region to a byte array.
bool canSendAuthzid() const
An Authorization ID can be sent if desired.
Simple Authentication and Security Layer protocol implementation.
Definition qca_securelayer.h:832
void setUsername(const QString &user)
Specify the username to use in authentication.
void continueAfterParams()
Continue negotiation after parameters have been set (client)
void write(const QByteArray &a) override
This method writes unencrypted (plain) data to the SecureLayer implementation.
void startClient(const QString &service, const QString &host, const QStringList &mechlist, ClientSendMode mode=AllowClientSendFirst)
Initialise the client side of the connection.
void setConstraints(AuthFlags f, SecurityLevel s=SL_None)
Specify connection constraints.
void setAuthzid(const QString &auth)
Specify the authorization identity to use in authentication.
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 writeIncoming(const QByteArray &a) override
This method accepts encoded (typically encrypted) data for processing.
void setPassword(const SecureArray &pass)
Specify the password to use in authentication.
void clientStarted(bool clientInit, const QByteArray &clientInitData)
This signal is emitted when the client has been successfully started.
QByteArray read() override
This method reads decrypted (plain) data from the SecureLayer implementation.
void needParams(const QCA::SASL::Params ¶ms)
This signal is emitted when the client needs additional parameters.
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.
MemoryRegion stringToArray(const QString &s)
Process an string in the "reverse" direction, returning a byte array.
Type type(const QSqlDatabase &db)
void init(KXmlGuiWindow *window, KGameDifficulty *difficulty=nullptr)
KIOCORE_EXPORT QStringList list(const QString &fileClass)
QCA_EXPORT bool isSupported(const char *features, const QString &provider=QString())
Test if a capability (algorithm) is available.
SocketError
void connectToHost(const QHostAddress &address, quint16 port, OpenMode openMode)
void connected()
SocketError error() const const
void errorOccurred(QAbstractSocket::SocketError socketError)
qsizetype indexOf(QByteArrayView bv, qsizetype from) const const
bool isEmpty() const const
QByteArray mid(qsizetype pos, qsizetype len) const const
qsizetype size() const const
void quit()
virtual bool canReadLine() const const
QByteArray readAll()
QByteArray readLine(qint64 maxSize)
void readyRead()
qint64 write(const QByteArray &data)
qsizetype count() const const
bool isEmpty() const const
QList< T > mid(qsizetype pos, qsizetype length) const const
void removeAt(qsizetype i)
void removeFirst()
bool invokeMethod(QObject *context, Functor &&function, FunctorReturnType *ret)
Q_OBJECTQ_OBJECT
Q_SIGNALSQ_SIGNALS
Q_SLOTSQ_SLOTS
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
bool disconnect(const QMetaObject::Connection &connection)
QString fromLatin1(QByteArrayView str)
QString fromUtf8(QByteArrayView str)
qsizetype indexOf(QChar ch, qsizetype from, Qt::CaseSensitivity cs) const const
bool isEmpty() const const
qsizetype length() const const
QString mid(qsizetype position, qsizetype n) const const
QStringList split(QChar sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const const
int toInt(bool *ok, int base) const const
QByteArray toUtf8() const const
void truncate(qsizetype position)
QStringView mid(qsizetype start, qsizetype length) const const
int toInt(bool *ok, int base) const const
QueuedConnection
singleShot
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Mon Nov 18 2024 12:15:56 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006
Documentation copyright © 1996-2024 The KDE developers.
Generated on Mon Nov 18 2024 12:15:56 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006
KDE's Doxygen guidelines are available online.