qa: Replace deprecated qVariantFromValue() by QVariant::fromValue()
[quassel.git] / src / core / sslserver.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 "sslserver.h"
22
23 #ifdef HAVE_SSL
24 #    include <QSslSocket>
25 #endif
26
27 #include <QDateTime>
28
29 #include "core.h"
30 #include "quassel.h"
31
32 #ifdef HAVE_SSL
33
34 SslServer::SslServer(QObject* parent)
35     : QTcpServer(parent)
36 {
37     // Keep track if the SSL warning has been mentioned at least once before
38     static bool sslWarningShown = false;
39
40     if (Quassel::isOptionSet("ssl-cert")) {
41         _sslCertPath = Quassel::optionValue("ssl-cert");
42     }
43     else {
44         _sslCertPath = Quassel::configDirPath() + "quasselCert.pem";
45     }
46
47     if (Quassel::isOptionSet("ssl-key")) {
48         _sslKeyPath = Quassel::optionValue("ssl-key");
49     }
50     else {
51         _sslKeyPath = _sslCertPath;
52     }
53
54     // Initialize the certificates for first-time usage
55     if (!loadCerts()) {
56         if (!sslWarningShown) {
57             qWarning() << "SslServer: Unable to set certificate file\n"
58                        << "          Quassel Core will still work, but cannot provide SSL for client connections.\n"
59                        << "          Please see https://quassel-irc.org/faq/cert to learn how to enable SSL support.";
60             sslWarningShown = true;
61         }
62     }
63 }
64
65 QTcpSocket* SslServer::nextPendingConnection()
66 {
67     if (_pendingConnections.isEmpty())
68         return nullptr;
69     else
70         return _pendingConnections.takeFirst();
71 }
72
73 void SslServer::incomingConnection(qintptr socketDescriptor)
74 {
75     auto* serverSocket = new QSslSocket(this);
76     if (serverSocket->setSocketDescriptor(socketDescriptor)) {
77         if (isCertValid()) {
78             serverSocket->setLocalCertificate(_cert);
79             serverSocket->setPrivateKey(_key);
80             serverSocket->addCaCertificates(_ca);
81         }
82         _pendingConnections << serverSocket;
83         emit newConnection();
84     }
85     else {
86         delete serverSocket;
87     }
88 }
89
90 bool SslServer::loadCerts()
91 {
92     // Load the certificates specified in the path.  If needed, other prep work can be done here.
93     return setCertificate(_sslCertPath, _sslKeyPath);
94 }
95
96 bool SslServer::reloadCerts()
97 {
98     if (loadCerts()) {
99         return true;
100     }
101     else {
102         // Reloading certificates currently only occur in response to a request.  Always print an
103         // error if something goes wrong, in order to simplify checking if it's working.
104         if (isCertValid()) {
105             qWarning() << "SslServer: Unable to reload certificate file, reverting\n"
106                        << "          Quassel Core will use the previous key to provide SSL for client connections.\n"
107                        << "          Please see https://quassel-irc.org/faq/cert to learn how to enable SSL support.";
108         }
109         else {
110             qWarning() << "SslServer: Unable to reload certificate file\n"
111                        << "          Quassel Core will still work, but cannot provide SSL for client connections.\n"
112                        << "          Please see https://quassel-irc.org/faq/cert to learn how to enable SSL support.";
113         }
114         return false;
115     }
116 }
117
118 bool SslServer::setCertificate(const QString& path, const QString& keyPath)
119 {
120     // Don't reset _isCertValid here, in case an older but valid certificate is still loaded.
121     // Use temporary variables in order to avoid overwriting the existing certificates until
122     // everything is confirmed good.
123     QSslCertificate untestedCert;
124     QList<QSslCertificate> untestedCA;
125     QSslKey untestedKey;
126
127     if (path.isEmpty())
128         return false;
129
130     QFile certFile(path);
131     if (!certFile.exists()) {
132         qWarning() << "SslServer: Certificate file" << qPrintable(path) << "does not exist";
133         return false;
134     }
135
136     if (!certFile.open(QIODevice::ReadOnly)) {
137         qWarning() << "SslServer: Failed to open certificate file" << qPrintable(path) << "error:" << certFile.error();
138         return false;
139     }
140
141     QList<QSslCertificate> certList = QSslCertificate::fromDevice(&certFile);
142
143     if (certList.isEmpty()) {
144         qWarning() << "SslServer: Certificate file doesn't contain a certificate";
145         return false;
146     }
147
148     untestedCert = certList[0];
149     certList.removeFirst();  // remove server cert
150
151     // store CA and intermediates certs
152     untestedCA = certList;
153
154     if (!certFile.reset()) {
155         qWarning() << "SslServer: IO error reading certificate file";
156         return false;
157     }
158
159     // load key from keyPath if it differs from path, otherwise load key from path
160     if (path != keyPath) {
161         QFile keyFile(keyPath);
162         if (!keyFile.exists()) {
163             qWarning() << "SslServer: Key file" << qPrintable(keyPath) << "does not exist";
164             return false;
165         }
166
167         if (!keyFile.open(QIODevice::ReadOnly)) {
168             qWarning() << "SslServer: Failed to open key file" << qPrintable(keyPath) << "error:" << keyFile.error();
169             return false;
170         }
171
172         untestedKey = loadKey(&keyFile);
173         keyFile.close();
174     }
175     else {
176         untestedKey = loadKey(&certFile);
177     }
178
179     certFile.close();
180
181     if (untestedCert.isNull()) {
182         qWarning() << "SslServer:" << qPrintable(path) << "contains no certificate data";
183         return false;
184     }
185
186     // We allow the core to offer SSL anyway, so no "return false" here. Client will warn about the cert being invalid.
187     const QDateTime now = QDateTime::currentDateTime();
188     if (now < untestedCert.effectiveDate()) {
189         qWarning() << "SslServer: Certificate won't be valid before" << untestedCert.effectiveDate().toString();
190     }
191     else if (now > untestedCert.expiryDate()) {
192         qWarning() << "SslServer: Certificate expired on" << untestedCert.expiryDate().toString();
193     }
194     else if (untestedCert.isBlacklisted()) {
195         qWarning() << "SslServer: Certificate blacklisted";
196     }
197
198     if (untestedKey.isNull()) {
199         qWarning() << "SslServer:" << qPrintable(keyPath) << "contains no key data";
200         return false;
201     }
202
203     _certificateExpires = untestedCert.expiryDate();
204     if (_metricsServer) {
205         _metricsServer->setCertificateExpires(_certificateExpires);
206     }
207
208     _isCertValid = true;
209
210     // All keys are valid, update the externally visible copy used for new connections.
211     _cert = untestedCert;
212     _ca = untestedCA;
213     _key = untestedKey;
214
215     return _isCertValid;
216 }
217
218 QSslKey SslServer::loadKey(QFile* keyFile)
219 {
220     QSslKey key;
221     key = QSslKey(keyFile, QSsl::Rsa);
222     if (key.isNull()) {
223         if (!keyFile->reset()) {
224             qWarning() << "SslServer: IO error reading key file";
225             return key;
226         }
227         key = QSslKey(keyFile, QSsl::Ec);
228     }
229     return key;
230 }
231
232 void SslServer::setMetricsServer(MetricsServer* metricsServer) {
233     _metricsServer = metricsServer;
234     if (_metricsServer) {
235         _metricsServer->setCertificateExpires(_certificateExpires);
236     }
237 }
238
239 #endif  // HAVE_SSL