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