]> granicus.if.org Git - icinga2/blob - lib/base/tlsstream.cpp
Merge pull request #6639 from Icinga/fix/windows-api-log-rename
[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 "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, this), 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                 bool corked = IsCorked();
157                 if (!corked && (revents & (POLLIN | POLLERR | POLLHUP)))
158                         m_CurrentAction = TlsActionRead;
159                 else if (m_SendQ->GetAvailableBytes() > 0 && (revents & POLLOUT))
160                         m_CurrentAction = TlsActionWrite;
161                 else {
162                         if (corked)
163                                 ChangeEvents(0);
164                         else
165                                 ChangeEvents(POLLIN);
166
167                         return;
168                 }
169         }
170
171         bool success = false;
172
173         /* Clear error queue for this thread before using SSL_{read,write,do_handshake}.
174          * Otherwise SSL_*_error() does not work reliably.
175          */
176         ERR_clear_error();
177
178         size_t readTotal = 0;
179
180         switch (m_CurrentAction) {
181                 case TlsActionRead:
182                         do {
183                                 rc = SSL_read(m_SSL.get(), buffer, sizeof(buffer));
184
185                                 if (rc > 0) {
186                                         m_RecvQ->Write(buffer, rc);
187                                         success = true;
188
189                                         readTotal += rc;
190                                 }
191
192 #ifdef I2_DEBUG /* I2_DEBUG */
193                                 Log(LogDebug, "TlsStream")
194                                         << "Read bytes: " << rc << " Total read bytes: " << readTotal;
195 #endif /* I2_DEBUG */
196                                 /* Limit read size. We cannot do this check inside the while loop
197                                  * since below should solely check whether OpenSSL has more data
198                                  * or not. */
199                                 if (readTotal >= 64 * 1024) {
200 #ifdef I2_DEBUG /* I2_DEBUG */
201                                         Log(LogWarning, "TlsStream")
202                                                 << "Maximum read bytes exceeded: " << readTotal;
203 #endif /* I2_DEBUG */
204                                         break;
205                                 }
206
207                         /* Use OpenSSL's state machine here to determine whether we need
208                          * to read more data. SSL_has_pending() is available with 1.1.0.
209                          */
210                         } while (SSL_pending(m_SSL.get()));
211
212                         if (success)
213                                 m_CV.notify_all();
214
215                         break;
216                 case TlsActionWrite:
217                         count = m_SendQ->Peek(buffer, sizeof(buffer), true);
218
219                         rc = SSL_write(m_SSL.get(), buffer, count);
220
221                         if (rc > 0) {
222                                 m_SendQ->Read(nullptr, rc, true);
223                                 success = true;
224                         }
225
226                         break;
227                 case TlsActionHandshake:
228                         rc = SSL_do_handshake(m_SSL.get());
229
230                         if (rc > 0) {
231                                 success = true;
232                                 m_HandshakeOK = true;
233                                 m_CV.notify_all();
234                         }
235
236                         break;
237                 default:
238                         VERIFY(!"Invalid TlsAction");
239         }
240
241         if (rc <= 0) {
242                 int err = SSL_get_error(m_SSL.get(), rc);
243
244                 switch (err) {
245                         case SSL_ERROR_WANT_READ:
246                                 m_Retry = true;
247                                 ChangeEvents(POLLIN);
248
249                                 break;
250                         case SSL_ERROR_WANT_WRITE:
251                                 m_Retry = true;
252                                 ChangeEvents(POLLOUT);
253
254                                 break;
255                         case SSL_ERROR_ZERO_RETURN:
256                                 lock.unlock();
257
258                                 Close();
259
260                                 return;
261                         default:
262                                 m_ErrorCode = ERR_peek_error();
263                                 m_ErrorOccurred = true;
264
265                                 if (m_ErrorCode != 0) {
266                                         Log(LogWarning, "TlsStream")
267                                                 << "OpenSSL error: " << ERR_error_string(m_ErrorCode, nullptr);
268                                 } else {
269                                         Log(LogWarning, "TlsStream", "TLS stream was disconnected.");
270                                 }
271
272                                 lock.unlock();
273
274                                 Close();
275
276                                 return;
277                 }
278         }
279
280         if (success) {
281                 m_CurrentAction = TlsActionNone;
282
283                 if (!m_Eof) {
284                         if (m_SendQ->GetAvailableBytes() > 0)
285                                 ChangeEvents(POLLIN|POLLOUT);
286                         else
287                                 ChangeEvents(POLLIN);
288                 }
289
290                 lock.unlock();
291
292                 while (!IsCorked() && m_RecvQ->IsDataAvailable() && IsHandlingEvents())
293                         SignalDataAvailable();
294         }
295
296         if (m_Shutdown && !m_SendQ->IsDataAvailable()) {
297                 if (!success)
298                         lock.unlock();
299
300                 Close();
301         }
302 }
303
304 void TlsStream::HandleError() const
305 {
306         if (m_ErrorOccurred) {
307                 BOOST_THROW_EXCEPTION(openssl_error()
308                         << boost::errinfo_api_function("TlsStream::OnEvent")
309                         << errinfo_openssl_error(m_ErrorCode));
310         }
311 }
312
313 void TlsStream::Handshake()
314 {
315         boost::mutex::scoped_lock lock(m_Mutex);
316
317         m_CurrentAction = TlsActionHandshake;
318         ChangeEvents(POLLOUT);
319
320         boost::system_time const timeout = boost::get_system_time() + boost::posix_time::milliseconds(long(Configuration::TlsHandshakeTimeout * 1000));
321
322         while (!m_HandshakeOK && !m_ErrorOccurred && !m_Eof && timeout > boost::get_system_time())
323                 m_CV.timed_wait(lock, timeout);
324
325         if (timeout < boost::get_system_time())
326                 BOOST_THROW_EXCEPTION(std::runtime_error("Timeout was reached (" + Convert::ToString(Configuration::TlsHandshakeTimeout) + ") during TLS handshake."));
327
328         if (m_Eof)
329                 BOOST_THROW_EXCEPTION(std::runtime_error("Socket was closed during TLS handshake."));
330
331         HandleError();
332 }
333
334 /**
335  * Processes data for the stream.
336  */
337 size_t TlsStream::Peek(void *buffer, size_t count, bool allow_partial)
338 {
339         boost::mutex::scoped_lock lock(m_Mutex);
340
341         if (!allow_partial)
342                 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
343                         m_CV.wait(lock);
344
345         HandleError();
346
347         return m_RecvQ->Peek(buffer, count, true);
348 }
349
350 size_t TlsStream::Read(void *buffer, size_t count, bool allow_partial)
351 {
352         boost::mutex::scoped_lock lock(m_Mutex);
353
354         if (!allow_partial)
355                 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
356                         m_CV.wait(lock);
357
358         HandleError();
359
360         return m_RecvQ->Read(buffer, count, true);
361 }
362
363 void TlsStream::Write(const void *buffer, size_t count)
364 {
365         boost::mutex::scoped_lock lock(m_Mutex);
366
367         m_SendQ->Write(buffer, count);
368
369         ChangeEvents(POLLIN|POLLOUT);
370 }
371
372 void TlsStream::Shutdown()
373 {
374         m_Shutdown = true;
375         ChangeEvents(POLLOUT);
376 }
377
378 /**
379  * Closes the stream.
380  */
381 void TlsStream::Close()
382 {
383         CloseInternal(false);
384 }
385
386 void TlsStream::CloseInternal(bool inDestructor)
387 {
388         if (m_Eof)
389                 return;
390
391         m_Eof = true;
392
393         if (!inDestructor)
394                 SignalDataAvailable();
395
396         SocketEvents::Unregister();
397
398         Stream::Close();
399
400         boost::mutex::scoped_lock lock(m_Mutex);
401
402         if (!m_SSL)
403                 return;
404
405         (void)SSL_shutdown(m_SSL.get());
406         m_SSL.reset();
407
408         m_Socket->Close();
409         m_Socket.reset();
410
411         m_CV.notify_all();
412 }
413
414 bool TlsStream::IsEof() const
415 {
416         return m_Eof && m_RecvQ->GetAvailableBytes() < 1u;
417 }
418
419 bool TlsStream::SupportsWaiting() const
420 {
421         return true;
422 }
423
424 bool TlsStream::IsDataAvailable() const
425 {
426         boost::mutex::scoped_lock lock(m_Mutex);
427
428         return m_RecvQ->GetAvailableBytes() > 0;
429 }
430
431 void TlsStream::SetCorked(bool corked)
432 {
433         Stream::SetCorked(corked);
434
435         boost::mutex::scoped_lock lock(m_Mutex);
436
437         if (corked)
438                 m_CurrentAction = TlsActionNone;
439         else
440                 ChangeEvents(POLLIN | POLLOUT);
441 }
442
443 Socket::Ptr TlsStream::GetSocket() const
444 {
445         return m_Socket;
446 }