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