common: Represent core/client features as string list in the protocol
[quassel.git] / src / client / clientauthhandler.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include "clientauthhandler.h"
22
23 // TODO: support system application proxy (new in Qt 4.6)
24
25 #include <QtEndian>
26
27 #ifdef HAVE_SSL
28     #include <QSslSocket>
29 #else
30     #include <QTcpSocket>
31 #endif
32
33 #include "client.h"
34 #include "clientsettings.h"
35 #include "logger.h"
36 #include "peerfactory.h"
37
38 #if QT_VERSION < 0x050000
39 #    include "../../3rdparty/sha512/sha512.h"
40 #endif
41
42 using namespace Protocol;
43
44 ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject *parent)
45     : AuthHandler(parent),
46     _peer(nullptr),
47     _account(account),
48     _probing(false),
49     _legacy(false),
50     _connectionFeatures(0)
51 {
52
53 }
54
55
56 Peer *ClientAuthHandler::peer() const
57 {
58     return _peer;
59 }
60
61
62 void ClientAuthHandler::connectToCore()
63 {
64     CoreAccountSettings s;
65
66 #ifdef HAVE_SSL
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);
70 #else
71     if (_account.useSsl()) {
72         if (s.accountValue("ShowNoClientSslWarning", true).toBool()) {
73             bool accepted = false;
74             emit handleNoSslInClient(&accepted);
75             if (!accepted) {
76                 emit errorMessage(tr("Unencrypted connection canceled"));
77                 return;
78             }
79             s.setAccountValue("ShowNoClientSslWarning", false);
80         }
81     }
82     QTcpSocket *socket = new QTcpSocket(this);
83 #endif
84
85 #ifndef QT_NO_NETWORKPROXY
86     QNetworkProxy proxy;
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());
94     }
95
96     if (_account.proxyType() == QNetworkProxy::DefaultProxy) {
97         QNetworkProxyFactory::setUseSystemConfiguration(true);
98     } else {
99         QNetworkProxyFactory::setUseSystemConfiguration(false);
100         socket->setProxy(proxy);
101     }
102 #endif
103
104     setSocket(socket);
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()));
108
109     emit statusMessage(tr("Connecting to %1...").arg(_account.accountName()));
110     socket->connectToHost(_account.hostName(), _account.port());
111 }
112
113
114 void ClientAuthHandler::onSocketStateChanged(QAbstractSocket::SocketState socketState)
115 {
116     QString text;
117
118     switch(socketState) {
119         case QAbstractSocket::HostLookupState:
120             if (!_legacy)
121                 text = tr("Looking up %1...").arg(_account.hostName());
122             break;
123         case QAbstractSocket::ConnectingState:
124             if (!_legacy)
125                 text = tr("Connecting to %1...").arg(_account.hostName());
126             break;
127         case QAbstractSocket::ConnectedState:
128             text = tr("Connected to %1").arg(_account.hostName());
129             break;
130         case QAbstractSocket::ClosingState:
131             if (!_probing)
132                 text = tr("Disconnecting from %1...").arg(_account.hostName());
133             break;
134         case QAbstractSocket::UnconnectedState:
135             if (!_probing) {
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()));
142             }
143             break;
144         default:
145             break;
146     }
147
148     if (!text.isEmpty()) {
149         emit statusMessage(text);
150     }
151 }
152
153 void ClientAuthHandler::onSocketError(QAbstractSocket::SocketError error)
154 {
155     if (_probing && error == QAbstractSocket::RemoteHostClosedError) {
156         _legacy = true;
157         return;
158     }
159
160     _probing = false; // all other errors are unrelated to probing and should be handled
161     AuthHandler::onSocketError(error);
162 }
163
164
165 void ClientAuthHandler::onSocketDisconnected()
166 {
167     if (_probing && _legacy) {
168         // Remote host has closed the connection while probing
169         _probing = false;
170         disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
171         emit statusMessage(tr("Reconnecting in compatibility mode..."));
172         socket()->connectToHost(_account.hostName(), _account.port());
173         return;
174     }
175
176     AuthHandler::onSocketDisconnected();
177 }
178
179
180 void ClientAuthHandler::onSocketConnected()
181 {
182     if (_peer) {
183         qWarning() << Q_FUNC_INFO << "Peer already exists!";
184         return;
185     }
186
187     socket()->setSocketOption(QAbstractSocket::KeepAliveOption, true);
188
189     if (!_legacy) {
190         // First connection attempt, try probing for a capable core
191         _probing = true;
192
193         QDataStream stream(socket()); // stream handles the endianness for us
194         stream.setVersion(QDataStream::Qt_4_2);
195
196         quint32 magic = Protocol::magic;
197 #ifdef HAVE_SSL
198         if (_account.useSsl())
199             magic |= Protocol::Encryption;
200 #endif
201         magic |= Protocol::Compression;
202
203         stream << magic;
204
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
212             stream << reply;
213         }
214
215         socket()->flush(); // make sure the probing data is sent immediately
216         return;
217     }
218
219     // If we arrive here, it's the second connection attempt, meaning probing was not successful -> enable legacy support
220
221     qDebug() << "Legacy core detected, switching to compatibility mode";
222
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)));
226
227     setPeer(peer);
228 }
229
230
231 void ClientAuthHandler::onReadyRead()
232 {
233     if (socket()->bytesAvailable() < 4)
234         return;
235
236     if (!_probing)
237         return; // make sure to not read more data than needed
238
239     _probing = false;
240     disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
241
242     quint32 reply;
243     socket()->read((char *)&reply, 4);
244     reply = qFromBigEndian<quint32>(reply);
245
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);
249
250     Compressor::CompressionLevel level;
251     if (_connectionFeatures & Protocol::Compression)
252         level = Compressor::BestCompression;
253     else
254         level = Compressor::NoCompression;
255
256     RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), level, this);
257     if (!peer) {
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."));
261
262         requestDisconnect(tr("Core speaks none of the protocols we support"));
263         return;
264     }
265
266     if (peer->protocol() == Protocol::LegacyProtocol) {
267         connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
268         _legacy = true;
269     }
270
271     setPeer(peer);
272 }
273
274
275 void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected)
276 {
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"));
280 }
281
282
283 void ClientAuthHandler::setPeer(RemotePeer *peer)
284 {
285     qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
286
287     _peer = peer;
288     connect(_peer, SIGNAL(transferProgress(int,int)), SIGNAL(transferProgress(int,int)));
289
290     // The legacy protocol enables SSL later, after registration
291     if (!_account.useSsl() || _legacy)
292         startRegistration();
293     // otherwise, do it now
294     else
295         checkAndEnableSsl(_connectionFeatures & Protocol::Encryption);
296 }
297
298
299 void ClientAuthHandler::startRegistration()
300 {
301     emit statusMessage(tr("Synchronizing to core..."));
302
303     // useSsl will be ignored by non-legacy peers
304     bool useSsl = false;
305 #ifdef HAVE_SSL
306     useSsl = _account.useSsl();
307 #endif
308
309     _peer->dispatch(RegisterClient(Quassel::Features{}, Quassel::buildInfo().fancyVersionString, Quassel::buildInfo().commitDate, useSsl));
310 }
311
312
313 void ClientAuthHandler::handle(const ClientDenied &msg)
314 {
315     emit errorPopup(msg.errorString);
316     requestDisconnect(tr("The core refused connection from this client"));
317 }
318
319
320 void ClientAuthHandler::handle(const ClientRegistered &msg)
321 {
322     _coreConfigured = msg.coreConfigured;
323     _backendInfo = msg.backendInfo;
324     _authenticatorInfo = msg.authenticatorInfo;
325
326     _peer->setFeatures(std::move(msg.features));
327
328     // The legacy protocol enables SSL at this point
329     if(_legacy && _account.useSsl())
330         checkAndEnableSsl(msg.sslSupported);
331     else
332         onConnectionReady();
333 }
334
335
336 void ClientAuthHandler::onConnectionReady()
337 {
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(", ")));
342     }
343     if (!coreFeatures.unknownFeatures().isEmpty()) {
344         quInfo() << qPrintable(tr("Core supports unknown features: %1").arg(coreFeatures.unknownFeatures().join(", ")));
345     }
346
347     emit connectionReady();
348     emit statusMessage(tr("Connected to %1").arg(_account.accountName()));
349
350     if (!_coreConfigured) {
351         // start wizard
352         emit startCoreSetup(_backendInfo, _authenticatorInfo);
353     }
354     else // TODO: check if we need LoginEnabled
355         login();
356 }
357
358
359 void ClientAuthHandler::setupCore(const SetupData &setupData)
360 {
361     _peer->dispatch(setupData);
362 }
363
364
365 void ClientAuthHandler::handle(const SetupFailed &msg)
366 {
367     emit coreSetupFailed(msg.errorString);
368 }
369
370
371 void ClientAuthHandler::handle(const SetupDone &msg)
372 {
373     Q_UNUSED(msg)
374
375     emit coreSetupSuccessful();
376 }
377
378
379 void ClientAuthHandler::login(const QString &user, const QString &password, bool remember)
380 {
381     _account.setUser(user);
382     _account.setPassword(password);
383     _account.setStorePassword(remember);
384     login();
385 }
386
387
388 void ClientAuthHandler::login(const QString &previousError)
389 {
390     emit statusMessage(tr("Logging in..."));
391     if (_account.user().isEmpty() || _account.password().isEmpty() || !previousError.isEmpty()) {
392         bool valid = false;
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"));
396             return;
397         }
398     }
399
400     _peer->dispatch(Login(_account.user(), _account.password()));
401 }
402
403
404 void ClientAuthHandler::handle(const LoginFailed &msg)
405 {
406     login(msg.errorString);
407 }
408
409
410 void ClientAuthHandler::handle(const LoginSuccess &msg)
411 {
412     Q_UNUSED(msg)
413
414     emit loginSuccessful(_account);
415 }
416
417
418 void ClientAuthHandler::handle(const SessionState &msg)
419 {
420     disconnect(socket(), 0, this, 0); // this is the last message we shall ever get
421
422     // give up ownership of the peer; CoreSession takes responsibility now
423     _peer->setParent(0);
424     emit handshakeComplete(_peer, msg);
425 }
426
427
428 /*** SSL Stuff ***/
429
430 void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl)
431 {
432 #ifndef HAVE_SSL
433     Q_UNUSED(coreSupportsSsl);
434 #else
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);
439
440         QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket());
441         Q_ASSERT(sslSocket);
442         connect(sslSocket, SIGNAL(encrypted()), SLOT(onSslSocketEncrypted()));
443         connect(sslSocket, SIGNAL(sslErrors(QList<QSslError>)), SLOT(onSslErrors()));
444         qDebug() << "Starting encryption...";
445         sslSocket->flush();
446         sslSocket->startClientEncryption();
447     }
448     else {
449         if (s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
450             bool accepted = false;
451             emit handleNoSslInCore(&accepted);
452             if (!accepted) {
453                 requestDisconnect(tr("Unencrypted connection cancelled"));
454                 return;
455             }
456             s.setAccountValue("ShowNoCoreSslWarning", false);
457             s.setAccountValue("SslCert", QString());
458             s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
459         }
460         if (_legacy)
461             onConnectionReady();
462         else
463             startRegistration();
464     }
465 #endif
466 }
467
468 #ifdef HAVE_SSL
469
470 void ClientAuthHandler::onSslSocketEncrypted()
471 {
472     QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
473     Q_ASSERT(socket);
474
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));
481     }
482
483     emit encrypted(true);
484
485     if (_legacy)
486         onConnectionReady();
487     else
488         startRegistration();
489 }
490
491
492 void ClientAuthHandler::onSslErrors()
493 {
494     QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
495     Q_ASSERT(socket);
496
497     CoreAccountSettings s;
498     QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
499     ClientAuthHandler::DigestVersion knownDigestVersion = static_cast<ClientAuthHandler::DigestVersion>(s.accountValue("SslCertDigestVersion").toInt());
500
501     QByteArray calculatedDigest;
502     switch (knownDigestVersion) {
503     case ClientAuthHandler::DigestVersion::Md5:
504         calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Md5);
505         break;
506
507     case ClientAuthHandler::DigestVersion::Sha2_512:
508 #if QT_VERSION >= 0x050000
509         calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Sha512);
510 #else
511         calculatedDigest = sha2_512(socket->peerCertificate().toDer());
512 #endif
513         break;
514
515     default:
516         qWarning() << "Certificate digest version" << QString(knownDigestVersion) << "is not supported";
517     }
518
519     if (knownDigest != calculatedDigest) {
520         bool accepted = false;
521         bool permanently = false;
522         emit handleSslErrors(socket, &accepted, &permanently);
523
524         if (!accepted) {
525             requestDisconnect(tr("Unencrypted connection canceled"));
526             return;
527         }
528
529         if (permanently) {
530 #if QT_VERSION >= 0x050000
531             s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
532 #else
533             s.setAccountValue("SslCert", sha2_512(socket->peerCertificate().toDer()));
534 #endif
535             s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
536         }
537         else {
538             s.setAccountValue("SslCert", QString());
539             s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
540         }
541     }
542     else if (knownDigestVersion != ClientAuthHandler::DigestVersion::Latest) {
543 #if QT_VERSION >= 0x050000
544         s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
545 #else
546         s.setAccountValue("SslCert", sha2_512(socket->peerCertificate().toDer()));
547 #endif
548         s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
549     }
550
551     socket->ignoreSslErrors();
552 }
553
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
560     // out of scope.
561     QByteArray result;
562     result.append((char*) output, 64);
563     return result;
564 }
565 #endif
566
567 #endif /* HAVE_SSL */