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