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