]> granicus.if.org Git - icinga2/blob - lib/base/tlsstream.cpp
Merge pull request #6748 from Icinga/bugfix/api-setup-fails-missing-confd
[icinga2] / lib / base / tlsstream.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2018 Icinga Development Team (https://icinga.com/)      *
4  *                                                                            *
5  * This program is free software; you can redistribute it and/or              *
6  * modify it under the terms of the GNU General Public License                *
7  * as published by the Free Software Foundation; either version 2             *
8  * of the License, or (at your option) any later version.                     *
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 Free Software Foundation     *
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.             *
18  ******************************************************************************/
19
20 #include "base/tlsstream.hpp"
21 #include "base/utility.hpp"
22 #include "base/exception.hpp"
23 #include "base/logger.hpp"
24 #include "base/configuration.hpp"
25 #include "base/convert.hpp"
26 #include <iostream>
27
28 #ifndef _WIN32
29 #       include <poll.h>
30 #endif /* _WIN32 */
31
32 #define TLS_TIMEOUT_SECONDS 10
33
34 using namespace icinga;
35
36 int TlsStream::m_SSLIndex;
37 bool TlsStream::m_SSLIndexInitialized = false;
38
39 /**
40  * Constructor for the TlsStream class.
41  *
42  * @param role The role of the client.
43  * @param sslContext The SSL context for the client.
44  */
45 TlsStream::TlsStream(const Socket::Ptr& socket, const String& hostname, ConnectionRole role, const std::shared_ptr<SSL_CTX>& sslContext)
46         : SocketEvents(socket), m_Eof(false), m_HandshakeOK(false), m_VerifyOK(true), m_ErrorCode(0),
47         m_ErrorOccurred(false),  m_Socket(socket), m_Role(role), m_SendQ(new FIFO()), m_RecvQ(new FIFO()),
48         m_CurrentAction(TlsActionNone), m_Retry(false), m_Shutdown(false)
49 {
50         std::ostringstream msgbuf;
51         char errbuf[120];
52
53         m_SSL = std::shared_ptr<SSL>(SSL_new(sslContext.get()), SSL_free);
54
55         if (!m_SSL) {
56                 msgbuf << "SSL_new() failed with code " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
57                 Log(LogCritical, "TlsStream", msgbuf.str());
58
59                 BOOST_THROW_EXCEPTION(openssl_error()
60                         << boost::errinfo_api_function("SSL_new")
61                         << errinfo_openssl_error(ERR_peek_error()));
62         }
63
64         if (!m_SSLIndexInitialized) {
65                 m_SSLIndex = SSL_get_ex_new_index(0, const_cast<char *>("TlsStream"), nullptr, nullptr, nullptr);
66                 m_SSLIndexInitialized = true;
67         }
68
69         SSL_set_ex_data(m_SSL.get(), m_SSLIndex, this);
70
71         SSL_set_verify(m_SSL.get(), SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, &TlsStream::ValidateCertificate);
72
73         socket->MakeNonBlocking();
74
75         SSL_set_fd(m_SSL.get(), socket->GetFD());
76
77         if (m_Role == RoleServer)
78                 SSL_set_accept_state(m_SSL.get());
79         else {
80 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
81                 if (!hostname.IsEmpty())
82                         SSL_set_tlsext_host_name(m_SSL.get(), hostname.CStr());
83 #endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
84
85                 SSL_set_connect_state(m_SSL.get());
86         }
87 }
88
89 TlsStream::~TlsStream()
90 {
91         CloseInternal(true);
92 }
93
94 int TlsStream::ValidateCertificate(int preverify_ok, X509_STORE_CTX *ctx)
95 {
96         auto *ssl = static_cast<SSL *>(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
97         auto *stream = static_cast<TlsStream *>(SSL_get_ex_data(ssl, m_SSLIndex));
98
99         if (!preverify_ok) {
100                 stream->m_VerifyOK = false;
101
102                 std::ostringstream msgbuf;
103                 int err = X509_STORE_CTX_get_error(ctx);
104                 msgbuf << "code " << err << ": " << X509_verify_cert_error_string(err);
105                 stream->m_VerifyError = msgbuf.str();
106         }
107
108         return 1;
109 }
110
111 bool TlsStream::IsVerifyOK() const
112 {
113         return m_VerifyOK;
114 }
115
116 String TlsStream::GetVerifyError() const
117 {
118         return m_VerifyError;
119 }
120
121 /**
122  * Retrieves the X509 certficate for this client.
123  *
124  * @returns The X509 certificate.
125  */
126 std::shared_ptr<X509> TlsStream::GetClientCertificate() const
127 {
128         boost::mutex::scoped_lock lock(m_Mutex);
129         return std::shared_ptr<X509>(SSL_get_certificate(m_SSL.get()), &Utility::NullDeleter);
130 }
131
132 /**
133  * Retrieves the X509 certficate for the peer.
134  *
135  * @returns The X509 certificate.
136  */
137 std::shared_ptr<X509> TlsStream::GetPeerCertificate() const
138 {
139         boost::mutex::scoped_lock lock(m_Mutex);
140         return std::shared_ptr<X509>(SSL_get_peer_certificate(m_SSL.get()), X509_free);
141 }
142
143 void TlsStream::OnEvent(int revents)
144 {
145         int rc;
146         size_t count;
147
148         boost::mutex::scoped_lock lock(m_Mutex);
149
150         if (!m_SSL)
151                 return;
152
153         char buffer[64 * 1024];
154
155         if (m_CurrentAction == TlsActionNone) {
156                 if (revents & (POLLIN | POLLERR | POLLHUP))
157                         m_CurrentAction = TlsActionRead;
158                 else if (m_SendQ->GetAvailableBytes() > 0 && (revents & POLLOUT))
159                         m_CurrentAction = TlsActionWrite;
160                 else {
161                         ChangeEvents(POLLIN);
162
163                         return;
164                 }
165         }
166
167         bool success = false;
168
169         /* Clear error queue for this thread before using SSL_{read,write,do_handshake}.
170          * Otherwise SSL_*_error() does not work reliably.
171          */
172         ERR_clear_error();
173
174         size_t readTotal = 0;
175
176         switch (m_CurrentAction) {
177                 case TlsActionRead:
178                         do {
179                                 rc = SSL_read(m_SSL.get(), buffer, sizeof(buffer));
180
181                                 if (rc > 0) {
182                                         m_RecvQ->Write(buffer, rc);
183                                         success = true;
184
185                                         readTotal += rc;
186                                 }
187
188 #ifdef I2_DEBUG /* I2_DEBUG */
189                                 Log(LogDebug, "TlsStream")
190                                         << "Read bytes: " << rc << " Total read bytes: " << readTotal;
191 #endif /* I2_DEBUG */
192                                 /* Limit read size. We cannot do this check inside the while loop
193                                  * since below should solely check whether OpenSSL has more data
194                                  * or not. */
195                                 if (readTotal >= 64 * 1024) {
196 #ifdef I2_DEBUG /* I2_DEBUG */
197                                         Log(LogWarning, "TlsStream")
198                                                 << "Maximum read bytes exceeded: " << readTotal;
199 #endif /* I2_DEBUG */
200                                         break;
201                                 }
202
203                         /* Use OpenSSL's state machine here to determine whether we need
204                          * to read more data. SSL_has_pending() is available with 1.1.0.
205                          */
206                         } while (SSL_pending(m_SSL.get()));
207
208                         if (success)
209                                 m_CV.notify_all();
210
211                         break;
212                 case TlsActionWrite:
213                         count = m_SendQ->Peek(buffer, sizeof(buffer), true);
214
215                         rc = SSL_write(m_SSL.get(), buffer, count);
216
217                         if (rc > 0) {
218                                 m_SendQ->Read(nullptr, rc, true);
219                                 success = true;
220                         }
221
222                         break;
223                 case TlsActionHandshake:
224                         rc = SSL_do_handshake(m_SSL.get());
225
226                         if (rc > 0) {
227                                 success = true;
228                                 m_HandshakeOK = true;
229                                 m_CV.notify_all();
230                         }
231
232                         break;
233                 default:
234                         VERIFY(!"Invalid TlsAction");
235         }
236
237         if (rc <= 0) {
238                 int err = SSL_get_error(m_SSL.get(), rc);
239
240                 switch (err) {
241                         case SSL_ERROR_WANT_READ:
242                                 m_Retry = true;
243                                 ChangeEvents(POLLIN);
244
245                                 break;
246                         case SSL_ERROR_WANT_WRITE:
247                                 m_Retry = true;
248                                 ChangeEvents(POLLOUT);
249
250                                 break;
251                         case SSL_ERROR_ZERO_RETURN:
252                                 lock.unlock();
253
254                                 Close();
255
256                                 return;
257                         default:
258                                 m_ErrorCode = ERR_peek_error();
259                                 m_ErrorOccurred = true;
260
261                                 if (m_ErrorCode != 0) {
262                                         Log(LogWarning, "TlsStream")
263                                                 << "OpenSSL error: " << ERR_error_string(m_ErrorCode, nullptr);
264                                 } else {
265                                         Log(LogWarning, "TlsStream", "TLS stream was disconnected.");
266                                 }
267
268                                 lock.unlock();
269
270                                 Close();
271
272                                 return;
273                 }
274         }
275
276         if (success) {
277                 m_CurrentAction = TlsActionNone;
278
279                 if (!m_Eof) {
280                         if (m_SendQ->GetAvailableBytes() > 0)
281                                 ChangeEvents(POLLIN|POLLOUT);
282                         else
283                                 ChangeEvents(POLLIN);
284                 }
285
286                 lock.unlock();
287
288                 while (m_RecvQ->IsDataAvailable() && IsHandlingEvents())
289                         SignalDataAvailable();
290         }
291
292         if (m_Shutdown && !m_SendQ->IsDataAvailable()) {
293                 if (!success)
294                         lock.unlock();
295
296                 Close();
297         }
298 }
299
300 void TlsStream::HandleError() const
301 {
302         if (m_ErrorOccurred) {
303                 BOOST_THROW_EXCEPTION(openssl_error()
304                         << boost::errinfo_api_function("TlsStream::OnEvent")
305                         << errinfo_openssl_error(m_ErrorCode));
306         }
307 }
308
309 void TlsStream::Handshake()
310 {
311         boost::mutex::scoped_lock lock(m_Mutex);
312
313         m_CurrentAction = TlsActionHandshake;
314         ChangeEvents(POLLOUT);
315
316         boost::system_time const timeout = boost::get_system_time() + boost::posix_time::milliseconds(long(Configuration::TlsHandshakeTimeout * 1000));
317
318         while (!m_HandshakeOK && !m_ErrorOccurred && !m_Eof && timeout > boost::get_system_time())
319                 m_CV.timed_wait(lock, timeout);
320
321         if (timeout < boost::get_system_time())
322                 BOOST_THROW_EXCEPTION(std::runtime_error("Timeout was reached (" + Convert::ToString(Configuration::TlsHandshakeTimeout) + ") during TLS handshake."));
323
324         if (m_Eof)
325                 BOOST_THROW_EXCEPTION(std::runtime_error("Socket was closed during TLS handshake."));
326
327         HandleError();
328 }
329
330 /**
331  * Processes data for the stream.
332  */
333 size_t TlsStream::Peek(void *buffer, size_t count, bool allow_partial)
334 {
335         boost::mutex::scoped_lock lock(m_Mutex);
336
337         if (!allow_partial)
338                 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
339                         m_CV.wait(lock);
340
341         HandleError();
342
343         return m_RecvQ->Peek(buffer, count, true);
344 }
345
346 size_t TlsStream::Read(void *buffer, size_t count, bool allow_partial)
347 {
348         boost::mutex::scoped_lock lock(m_Mutex);
349
350         if (!allow_partial)
351                 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
352                         m_CV.wait(lock);
353
354         HandleError();
355
356         return m_RecvQ->Read(buffer, count, true);
357 }
358
359 void TlsStream::Write(const void *buffer, size_t count)
360 {
361         boost::mutex::scoped_lock lock(m_Mutex);
362
363         m_SendQ->Write(buffer, count);
364
365         ChangeEvents(POLLIN|POLLOUT);
366 }
367
368 void TlsStream::Shutdown()
369 {
370         m_Shutdown = true;
371         ChangeEvents(POLLOUT);
372 }
373
374 /**
375  * Closes the stream.
376  */
377 void TlsStream::Close()
378 {
379         CloseInternal(false);
380 }
381
382 void TlsStream::CloseInternal(bool inDestructor)
383 {
384         if (m_Eof)
385                 return;
386
387         m_Eof = true;
388
389         if (!inDestructor)
390                 SignalDataAvailable();
391
392         SocketEvents::Unregister();
393
394         Stream::Close();
395
396         boost::mutex::scoped_lock lock(m_Mutex);
397
398         if (!m_SSL)
399                 return;
400
401         /* https://www.openssl.org/docs/manmaster/man3/SSL_shutdown.html
402          *
403          * It is recommended to do a bidirectional shutdown by checking
404          * the return value of SSL_shutdown() and call it again until
405          * it returns 1 or a fatal error. A maximum of 2x pending + 2x data
406          * is recommended.
407          */
408         int rc = 0;
409
410         for (int i = 0; i < 4; i++) {
411                 if ((rc = SSL_shutdown(m_SSL.get())))
412                         break;
413         }
414
415         m_SSL.reset();
416
417         m_Socket->Close();
418         m_Socket.reset();
419
420         m_CV.notify_all();
421 }
422
423 bool TlsStream::IsEof() const
424 {
425         return m_Eof && m_RecvQ->GetAvailableBytes() < 1u;
426 }
427
428 bool TlsStream::SupportsWaiting() const
429 {
430         return true;
431 }
432
433 bool TlsStream::IsDataAvailable() const
434 {
435         boost::mutex::scoped_lock lock(m_Mutex);
436
437         return m_RecvQ->GetAvailableBytes() > 0;
438 }
439
440 Socket::Ptr TlsStream::GetSocket() const
441 {
442         return m_Socket;
443 }