1 /***************************************************************************
2 * Copyright (C) 2005-2018 by the Quassel Project *
3 * devel@quassel-irc.org *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) version 3. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
21 #include "clientauthhandler.h"
23 // TODO: support system application proxy (new in Qt 4.6)
34 #include "clientsettings.h"
36 #include "peerfactory.h"
38 #if QT_VERSION < 0x050000
39 # include "../../3rdparty/sha512/sha512.h"
42 using namespace Protocol;
44 ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject *parent)
45 : AuthHandler(parent),
50 _connectionFeatures(0)
56 Peer *ClientAuthHandler::peer() const
62 void ClientAuthHandler::connectToCore()
64 CoreAccountSettings s;
67 QSslSocket *socket = new QSslSocket(this);
68 // make sure the warning is shown if we happen to connect without SSL support later
69 s.setAccountValue("ShowNoClientSslWarning", true);
71 if (_account.useSsl()) {
72 if (s.accountValue("ShowNoClientSslWarning", true).toBool()) {
73 bool accepted = false;
74 emit handleNoSslInClient(&accepted);
76 emit errorMessage(tr("Unencrypted connection canceled"));
79 s.setAccountValue("ShowNoClientSslWarning", false);
82 QTcpSocket *socket = new QTcpSocket(this);
85 #ifndef QT_NO_NETWORKPROXY
87 proxy.setType(_account.proxyType());
88 if (_account.proxyType() == QNetworkProxy::Socks5Proxy ||
89 _account.proxyType() == QNetworkProxy::HttpProxy) {
90 proxy.setHostName(_account.proxyHostName());
91 proxy.setPort(_account.proxyPort());
92 proxy.setUser(_account.proxyUser());
93 proxy.setPassword(_account.proxyPassword());
96 if (_account.proxyType() == QNetworkProxy::DefaultProxy) {
97 QNetworkProxyFactory::setUseSystemConfiguration(true);
99 QNetworkProxyFactory::setUseSystemConfiguration(false);
100 socket->setProxy(proxy);
105 connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(onSocketStateChanged(QAbstractSocket::SocketState)));
106 connect(socket, SIGNAL(readyRead()), SLOT(onReadyRead()));
107 connect(socket, SIGNAL(connected()), SLOT(onSocketConnected()));
109 emit statusMessage(tr("Connecting to %1...").arg(_account.accountName()));
110 socket->connectToHost(_account.hostName(), _account.port());
114 void ClientAuthHandler::onSocketStateChanged(QAbstractSocket::SocketState socketState)
118 switch(socketState) {
119 case QAbstractSocket::HostLookupState:
121 text = tr("Looking up %1...").arg(_account.hostName());
123 case QAbstractSocket::ConnectingState:
125 text = tr("Connecting to %1...").arg(_account.hostName());
127 case QAbstractSocket::ConnectedState:
128 text = tr("Connected to %1").arg(_account.hostName());
130 case QAbstractSocket::ClosingState:
132 text = tr("Disconnecting from %1...").arg(_account.hostName());
134 case QAbstractSocket::UnconnectedState:
136 text = tr("Disconnected");
137 // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet.
138 // The baseclass implementation will make sure to only send the signal once.
139 // However, we do want to prefer a potential socket error signal that may be on route already, so
140 // give this a chance to overtake us by spinning the loop...
141 QTimer::singleShot(0, this, SLOT(onSocketDisconnected()));
148 if (!text.isEmpty()) {
149 emit statusMessage(text);
153 void ClientAuthHandler::onSocketError(QAbstractSocket::SocketError error)
155 if (_probing && error == QAbstractSocket::RemoteHostClosedError) {
160 _probing = false; // all other errors are unrelated to probing and should be handled
161 AuthHandler::onSocketError(error);
165 void ClientAuthHandler::onSocketDisconnected()
167 if (_probing && _legacy) {
168 // Remote host has closed the connection while probing
170 disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
171 emit statusMessage(tr("Reconnecting in compatibility mode..."));
172 socket()->connectToHost(_account.hostName(), _account.port());
176 AuthHandler::onSocketDisconnected();
180 void ClientAuthHandler::onSocketConnected()
183 qWarning() << Q_FUNC_INFO << "Peer already exists!";
187 socket()->setSocketOption(QAbstractSocket::KeepAliveOption, true);
190 // First connection attempt, try probing for a capable core
193 QDataStream stream(socket()); // stream handles the endianness for us
194 stream.setVersion(QDataStream::Qt_4_2);
196 quint32 magic = Protocol::magic;
198 if (_account.useSsl())
199 magic |= Protocol::Encryption;
201 magic |= Protocol::Compression;
205 // here goes the list of protocols we support, in order of preference
206 PeerFactory::ProtoList protos = PeerFactory::supportedProtocols();
207 for (int i = 0; i < protos.count(); ++i) {
208 quint32 reply = protos[i].first;
209 reply |= protos[i].second<<8;
210 if (i == protos.count() - 1)
211 reply |= 0x80000000; // end list
215 socket()->flush(); // make sure the probing data is sent immediately
219 // If we arrive here, it's the second connection attempt, meaning probing was not successful -> enable legacy support
221 qDebug() << "Legacy core detected, switching to compatibility mode";
223 RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0), this, socket(), Compressor::NoCompression, this);
224 // Only needed for the legacy peer, as all others check the protocol version before instantiation
225 connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
231 void ClientAuthHandler::onReadyRead()
233 if (socket()->bytesAvailable() < 4)
237 return; // make sure to not read more data than needed
240 disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
243 socket()->read((char *)&reply, 4);
244 reply = qFromBigEndian<quint32>(reply);
246 Protocol::Type type = static_cast<Protocol::Type>(reply & 0xff);
247 quint16 protoFeatures = static_cast<quint16>(reply>>8 & 0xffff);
248 _connectionFeatures = static_cast<quint8>(reply>>24);
250 Compressor::CompressionLevel level;
251 if (_connectionFeatures & Protocol::Compression)
252 level = Compressor::BestCompression;
254 level = Compressor::NoCompression;
256 RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), level, this);
258 qWarning() << "No valid protocol supported for this core!";
259 emit errorPopup(tr("<b>Incompatible Quassel Core!</b><br>"
260 "None of the protocols this client speaks are supported by the core you are trying to connect to."));
262 requestDisconnect(tr("Core speaks none of the protocols we support"));
266 if (peer->protocol() == Protocol::LegacyProtocol) {
267 connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
275 void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected)
277 emit errorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
278 "We need at least protocol v%1, but the core speaks v%2 only.").arg(expected, actual));
279 requestDisconnect(tr("Incompatible protocol version, connection to core refused"));
283 void ClientAuthHandler::setPeer(RemotePeer *peer)
285 qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
288 connect(_peer, SIGNAL(transferProgress(int,int)), SIGNAL(transferProgress(int,int)));
290 // The legacy protocol enables SSL later, after registration
291 if (!_account.useSsl() || _legacy)
293 // otherwise, do it now
295 checkAndEnableSsl(_connectionFeatures & Protocol::Encryption);
299 void ClientAuthHandler::startRegistration()
301 emit statusMessage(tr("Synchronizing to core..."));
303 // useSsl will be ignored by non-legacy peers
306 useSsl = _account.useSsl();
309 _peer->dispatch(RegisterClient(Quassel::Features{}, Quassel::buildInfo().fancyVersionString, Quassel::buildInfo().commitDate, useSsl));
313 void ClientAuthHandler::handle(const ClientDenied &msg)
315 emit errorPopup(msg.errorString);
316 requestDisconnect(tr("The core refused connection from this client"));
320 void ClientAuthHandler::handle(const ClientRegistered &msg)
322 _coreConfigured = msg.coreConfigured;
323 _backendInfo = msg.backendInfo;
324 _authenticatorInfo = msg.authenticatorInfo;
326 _peer->setFeatures(std::move(msg.features));
328 // The legacy protocol enables SSL at this point
329 if(_legacy && _account.useSsl())
330 checkAndEnableSsl(msg.sslSupported);
336 void ClientAuthHandler::onConnectionReady()
338 const auto &coreFeatures = _peer->features();
339 auto unsupported = coreFeatures.toStringList(false);
340 if (!unsupported.isEmpty()) {
341 quInfo() << qPrintable(tr("Core does not support the following features: %1").arg(unsupported.join(", ")));
343 if (!coreFeatures.unknownFeatures().isEmpty()) {
344 quInfo() << qPrintable(tr("Core supports unknown features: %1").arg(coreFeatures.unknownFeatures().join(", ")));
347 emit connectionReady();
348 emit statusMessage(tr("Connected to %1").arg(_account.accountName()));
350 if (!_coreConfigured) {
352 emit startCoreSetup(_backendInfo, _authenticatorInfo);
354 else // TODO: check if we need LoginEnabled
359 void ClientAuthHandler::setupCore(const SetupData &setupData)
361 _peer->dispatch(setupData);
365 void ClientAuthHandler::handle(const SetupFailed &msg)
367 emit coreSetupFailed(msg.errorString);
371 void ClientAuthHandler::handle(const SetupDone &msg)
375 emit coreSetupSuccessful();
379 void ClientAuthHandler::login(const QString &user, const QString &password, bool remember)
381 _account.setUser(user);
382 _account.setPassword(password);
383 _account.setStorePassword(remember);
388 void ClientAuthHandler::login(const QString &previousError)
390 emit statusMessage(tr("Logging in..."));
391 if (_account.user().isEmpty() || _account.password().isEmpty() || !previousError.isEmpty()) {
393 emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call
394 if (!valid || _account.user().isEmpty() || _account.password().isEmpty()) {
395 requestDisconnect(tr("Login canceled"));
400 _peer->dispatch(Login(_account.user(), _account.password()));
404 void ClientAuthHandler::handle(const LoginFailed &msg)
406 login(msg.errorString);
410 void ClientAuthHandler::handle(const LoginSuccess &msg)
414 emit loginSuccessful(_account);
418 void ClientAuthHandler::handle(const SessionState &msg)
420 disconnect(socket(), 0, this, 0); // this is the last message we shall ever get
422 // give up ownership of the peer; CoreSession takes responsibility now
424 emit handshakeComplete(_peer, msg);
430 void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl)
433 Q_UNUSED(coreSupportsSsl);
435 CoreAccountSettings s;
436 if (coreSupportsSsl && _account.useSsl()) {
437 // Make sure the warning is shown next time we don't have SSL in the core
438 s.setAccountValue("ShowNoCoreSslWarning", true);
440 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket());
442 connect(sslSocket, SIGNAL(encrypted()), SLOT(onSslSocketEncrypted()));
443 connect(sslSocket, SIGNAL(sslErrors(QList<QSslError>)), SLOT(onSslErrors()));
444 qDebug() << "Starting encryption...";
446 sslSocket->startClientEncryption();
449 if (s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
450 bool accepted = false;
451 emit handleNoSslInCore(&accepted);
453 requestDisconnect(tr("Unencrypted connection cancelled"));
456 s.setAccountValue("ShowNoCoreSslWarning", false);
457 s.setAccountValue("SslCert", QString());
458 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
470 void ClientAuthHandler::onSslSocketEncrypted()
472 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
475 if (!socket->sslErrors().count()) {
476 // Cert is valid, so we don't want to store it as known
477 // That way, a warning will appear in case it becomes invalid at some point
478 CoreAccountSettings s;
479 s.setAccountValue("SSLCert", QString());
480 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
483 emit encrypted(true);
492 void ClientAuthHandler::onSslErrors()
494 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
497 CoreAccountSettings s;
498 QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
499 ClientAuthHandler::DigestVersion knownDigestVersion = static_cast<ClientAuthHandler::DigestVersion>(s.accountValue("SslCertDigestVersion").toInt());
501 QByteArray calculatedDigest;
502 switch (knownDigestVersion) {
503 case ClientAuthHandler::DigestVersion::Md5:
504 calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Md5);
507 case ClientAuthHandler::DigestVersion::Sha2_512:
508 #if QT_VERSION >= 0x050000
509 calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Sha512);
511 calculatedDigest = sha2_512(socket->peerCertificate().toDer());
516 qWarning() << "Certificate digest version" << QString(knownDigestVersion) << "is not supported";
519 if (knownDigest != calculatedDigest) {
520 bool accepted = false;
521 bool permanently = false;
522 emit handleSslErrors(socket, &accepted, &permanently);
525 requestDisconnect(tr("Unencrypted connection canceled"));
530 #if QT_VERSION >= 0x050000
531 s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
533 s.setAccountValue("SslCert", sha2_512(socket->peerCertificate().toDer()));
535 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
538 s.setAccountValue("SslCert", QString());
539 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
542 else if (knownDigestVersion != ClientAuthHandler::DigestVersion::Latest) {
543 #if QT_VERSION >= 0x050000
544 s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
546 s.setAccountValue("SslCert", sha2_512(socket->peerCertificate().toDer()));
548 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
551 socket->ignoreSslErrors();
554 #if QT_VERSION < 0x050000
555 QByteArray ClientAuthHandler::sha2_512(const QByteArray &input) {
556 unsigned char output[64];
557 sha512((unsigned char*) input.constData(), input.size(), output, false);
558 // QByteArray::fromRawData() cannot be used here because that constructor
559 // does not copy "output" and the data is clobbered when the variable goes
562 result.append((char*) output, 64);
567 #endif /* HAVE_SSL */