3514ecd15580e0c4b4faa0193f014bdfae721bb7
[quassel.git] / src / core / coreauthhandler.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 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 "coreauthhandler.h"
22
23 #ifdef HAVE_SSL
24 #    include <QSslSocket>
25 #endif
26
27 #include "core.h"
28
29 using namespace Protocol;
30
31 CoreAuthHandler::CoreAuthHandler(QTcpSocket* socket, QObject* parent)
32     : AuthHandler(parent)
33     , _peer(nullptr)
34     , _magicReceived(false)
35     , _legacy(false)
36     , _clientRegistered(false)
37     , _connectionFeatures(0)
38 {
39     setSocket(socket);
40     connect(socket, &QIODevice::readyRead, this, &CoreAuthHandler::onReadyRead);
41
42     // TODO: Timeout for the handshake phase
43 }
44
45 void CoreAuthHandler::onReadyRead()
46 {
47     if (socket()->bytesAvailable() < 4)
48         return;
49
50     // once we have selected a peer, we certainly don't want to read more data!
51     if (_peer)
52         return;
53
54     if (!_magicReceived) {
55         quint32 magic;
56         socket()->peek((char*)&magic, 4);
57         magic = qFromBigEndian<quint32>(magic);
58
59         if ((magic & 0xffffff00) != Protocol::magic) {
60             // no magic, assume legacy protocol
61             qDebug() << "Legacy client detected, switching to compatibility mode";
62             _legacy = true;
63             RemotePeer* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0),
64                                                        this,
65                                                        socket(),
66                                                        Compressor::NoCompression,
67                                                        this);
68             connect(peer, &RemotePeer::protocolVersionMismatch, this, &CoreAuthHandler::onProtocolVersionMismatch);
69             setPeer(peer);
70             return;
71         }
72
73         _magicReceived = true;
74         quint8 features = magic & 0xff;
75         // figure out which connection features we'll use based on the client's support
76         if (Core::sslSupported() && (features & Protocol::Encryption))
77             _connectionFeatures |= Protocol::Encryption;
78         if (features & Protocol::Compression)
79             _connectionFeatures |= Protocol::Compression;
80
81         socket()->read((char*)&magic, 4);  // read the 4 bytes we've just peeked at
82     }
83
84     // read the list of protocols supported by the client
85     while (socket()->bytesAvailable() >= 4 && _supportedProtos.size() < 16) {  // sanity check
86         quint32 data;
87         socket()->read((char*)&data, 4);
88         data = qFromBigEndian<quint32>(data);
89
90         auto type = static_cast<Protocol::Type>(data & 0xff);
91         auto protoFeatures = static_cast<quint16>(data >> 8 & 0xffff);
92         _supportedProtos.append(PeerFactory::ProtoDescriptor(type, protoFeatures));
93
94         if (data >= 0x80000000) {  // last protocol
95             Compressor::CompressionLevel level;
96             if (_connectionFeatures & Protocol::Compression)
97                 level = Compressor::BestCompression;
98             else
99                 level = Compressor::NoCompression;
100
101             RemotePeer* peer = PeerFactory::createPeer(_supportedProtos, this, socket(), level, this);
102             if (!peer) {
103                 qWarning() << "Received invalid handshake data from client" << socket()->peerAddress().toString();
104                 close();
105                 return;
106             }
107
108             if (peer->protocol() == Protocol::LegacyProtocol) {
109                 _legacy = true;
110                 connect(peer, &RemotePeer::protocolVersionMismatch, this, &CoreAuthHandler::onProtocolVersionMismatch);
111             }
112             setPeer(peer);
113
114             // inform the client
115             quint32 reply = peer->protocol() | peer->enabledFeatures() << 8 | _connectionFeatures << 24;
116             reply = qToBigEndian<quint32>(reply);
117             socket()->write((char*)&reply, 4);
118             socket()->flush();
119
120             if (!_legacy && (_connectionFeatures & Protocol::Encryption))
121                 startSsl();  // legacy peer enables it later
122             return;
123         }
124     }
125 }
126
127 void CoreAuthHandler::setPeer(RemotePeer* peer)
128 {
129     qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
130
131     _peer = peer;
132     disconnect(socket(), &QIODevice::readyRead, this, &CoreAuthHandler::onReadyRead);
133 }
134
135 // only in compat mode
136 void CoreAuthHandler::onProtocolVersionMismatch(int actual, int expected)
137 {
138     qWarning() << qPrintable(tr("Client")) << _peer->description() << qPrintable(tr("too old, rejecting."));
139     QString errorString = tr("<b>Your Quassel Client is too old!</b><br>"
140                              "This core needs at least client/core protocol version %1 (got: %2).<br>"
141                              "Please consider upgrading your client.")
142                               .arg(expected, actual);
143     _peer->dispatch(ClientDenied(errorString));
144     _peer->close();
145 }
146
147 bool CoreAuthHandler::checkClientRegistered()
148 {
149     if (!_clientRegistered) {
150         qWarning() << qPrintable(tr("Client")) << qPrintable(socket()->peerAddress().toString())
151                    << qPrintable(tr("did not send a registration message before trying to login, rejecting."));
152         _peer->dispatch(
153             ClientDenied(tr("<b>Client not initialized!</b><br>You need to send a registration message before trying to login.")));
154         _peer->close();
155         return false;
156     }
157     return true;
158 }
159
160 void CoreAuthHandler::handle(const RegisterClient& msg)
161 {
162     bool useSsl;
163     if (_legacy)
164         useSsl = Core::sslSupported() && msg.sslSupported;
165     else
166         useSsl = _connectionFeatures & Protocol::Encryption;
167
168     if (Quassel::isOptionSet("require-ssl") && !useSsl && !_peer->isLocal()) {
169         qInfo() << qPrintable(tr("SSL required but non-SSL connection attempt from %1").arg(socket()->peerAddress().toString()));
170         _peer->dispatch(ClientDenied(tr("<b>SSL is required!</b><br>You need to use SSL in order to connect to this core.")));
171         _peer->close();
172         return;
173     }
174
175     _peer->setFeatures(std::move(msg.features));
176     _peer->setBuildDate(msg.buildDate);
177     _peer->setClientVersion(msg.clientVersion);
178
179     QVariantList backends;
180     QVariantList authenticators;
181     bool configured = Core::isConfigured();
182     if (!configured) {
183         backends = Core::backendInfo();
184         if (_peer->hasFeature(Quassel::Feature::Authenticators)) {
185             authenticators = Core::authenticatorInfo();
186         }
187     }
188
189     _peer->dispatch(ClientRegistered(Quassel::Features{}, configured, backends, authenticators, useSsl));
190
191     // useSsl is only used for the legacy protocol
192     if (_legacy && useSsl)
193         startSsl();
194
195     _clientRegistered = true;
196 }
197
198 void CoreAuthHandler::handle(const SetupData& msg)
199 {
200     if (!checkClientRegistered())
201         return;
202
203     // The default parameter to authenticator is Database.
204     // Maybe this should be hardcoded elsewhere, i.e. as a define.
205     QString authenticator = msg.authenticator;
206     qInfo() << "[" << authenticator << "]";
207     if (authenticator.trimmed().isEmpty()) {
208         authenticator = QString("Database");
209     }
210
211     QString result = Core::setup(msg.adminUser, msg.adminPassword, msg.backend, msg.setupData, authenticator, msg.authSetupData);
212     if (!result.isEmpty())
213         _peer->dispatch(SetupFailed(result));
214     else
215         _peer->dispatch(SetupDone());
216 }
217
218 void CoreAuthHandler::handle(const Login& msg)
219 {
220     if (!checkClientRegistered())
221         return;
222
223     if (!Core::isConfigured()) {
224         qWarning() << qPrintable(tr("Client")) << qPrintable(socket()->peerAddress().toString())
225                    << qPrintable(tr("attempted to login before the core was configured, rejecting."));
226         _peer->dispatch(ClientDenied(
227             tr("<b>Attempted to login before core was configured!</b><br>The core must be configured before attempting to login.")));
228         return;
229     }
230
231     // First attempt local auth using the real username and password.
232     // If that fails, move onto the auth provider.
233     UserId uid = Core::validateUser(msg.user, msg.password);
234     if (uid == 0) {
235         uid = Core::authenticateUser(msg.user, msg.password);
236     }
237
238     if (uid == 0) {
239         qInfo() << qPrintable(tr("Invalid login attempt from %1 as \"%2\"").arg(socket()->peerAddress().toString(), msg.user));
240         _peer->dispatch(LoginFailed(tr(
241             "<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.")));
242         return;
243     }
244     _peer->dispatch(LoginSuccess());
245
246     qInfo() << qPrintable(tr("Client %1 initialized and authenticated successfully as \"%2\" (UserId: %3).")
247                           .arg(socket()->peerAddress().toString(), msg.user, QString::number(uid.toInt())));
248
249     const auto& clientFeatures = _peer->features();
250     auto unsupported = clientFeatures.toStringList(false);
251     if (!unsupported.isEmpty()) {
252         if (unsupported.contains("NoFeatures"))
253             qInfo() << qPrintable(tr("Client does not support extended features."));
254         else
255             qInfo() << qPrintable(tr("Client does not support the following features: %1").arg(unsupported.join(", ")));
256     }
257
258     if (!clientFeatures.unknownFeatures().isEmpty()) {
259         qInfo() << qPrintable(tr("Client supports unknown features: %1").arg(clientFeatures.unknownFeatures().join(", ")));
260     }
261
262     disconnect(socket(), nullptr, this, nullptr);
263     disconnect(_peer, nullptr, this, nullptr);
264     _peer->setParent(nullptr);  // Core needs to take care of this one now!
265
266     socket()->flush();  // Make sure all data is sent before handing over the peer (and socket) to the session thread (bug 682)
267     emit handshakeComplete(_peer, uid);
268 }
269
270 /*** SSL Stuff ***/
271
272 void CoreAuthHandler::startSsl()
273 {
274 #ifdef HAVE_SSL
275     auto* sslSocket = qobject_cast<QSslSocket*>(socket());
276     Q_ASSERT(sslSocket);
277
278     qDebug() << qPrintable(tr("Starting encryption for Client:")) << _peer->description();
279     connect(sslSocket, selectOverload<const QList<QSslError>&>(&QSslSocket::sslErrors), this, &CoreAuthHandler::onSslErrors);
280     sslSocket->flush();  // ensure that the write cache is flushed before we switch to ssl (bug 682)
281     sslSocket->startServerEncryption();
282 #endif /* HAVE_SSL */
283 }
284
285 #ifdef HAVE_SSL
286 void CoreAuthHandler::onSslErrors()
287 {
288     auto* sslSocket = qobject_cast<QSslSocket*>(socket());
289     Q_ASSERT(sslSocket);
290     sslSocket->ignoreSslErrors();
291 }
292 #endif