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