1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
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 <boost/asio/ssl/context.hpp>
16 #define TLS_TIMEOUT_SECONDS 10
18 using namespace icinga;
20 int TlsStream::m_SSLIndex;
21 bool TlsStream::m_SSLIndexInitialized = false;
24 * Constructor for the TlsStream class.
26 * @param role The role of the client.
27 * @param sslContext The SSL context for the client.
29 TlsStream::TlsStream(const Socket::Ptr& socket, const String& hostname, ConnectionRole role, const std::shared_ptr<SSL_CTX>& sslContext)
30 : TlsStream(socket, hostname, role, sslContext.get())
35 * Constructor for the TlsStream class.
37 * @param role The role of the client.
38 * @param sslContext The SSL context for the client.
40 TlsStream::TlsStream(const Socket::Ptr& socket, const String& hostname, ConnectionRole role, const std::shared_ptr<boost::asio::ssl::context>& sslContext)
41 : TlsStream(socket, hostname, role, sslContext->native_handle())
46 * Constructor for the TlsStream class.
48 * @param role The role of the client.
49 * @param sslContext The SSL context for the client.
51 TlsStream::TlsStream(const Socket::Ptr& socket, const String& hostname, ConnectionRole role, SSL_CTX* sslContext)
52 : SocketEvents(socket), m_Eof(false), m_HandshakeOK(false), m_VerifyOK(true), m_ErrorCode(0),
53 m_ErrorOccurred(false), m_Socket(socket), m_Role(role), m_SendQ(new FIFO()), m_RecvQ(new FIFO()),
54 m_CurrentAction(TlsActionNone), m_Retry(false), m_Shutdown(false)
56 std::ostringstream msgbuf;
59 m_SSL = std::shared_ptr<SSL>(SSL_new(sslContext), SSL_free);
62 msgbuf << "SSL_new() failed with code " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
63 Log(LogCritical, "TlsStream", msgbuf.str());
65 BOOST_THROW_EXCEPTION(openssl_error()
66 << boost::errinfo_api_function("SSL_new")
67 << errinfo_openssl_error(ERR_peek_error()));
70 if (!m_SSLIndexInitialized) {
71 m_SSLIndex = SSL_get_ex_new_index(0, const_cast<char *>("TlsStream"), nullptr, nullptr, nullptr);
72 m_SSLIndexInitialized = true;
75 SSL_set_ex_data(m_SSL.get(), m_SSLIndex, this);
77 SSL_set_verify(m_SSL.get(), SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, &TlsStream::ValidateCertificate);
79 socket->MakeNonBlocking();
81 SSL_set_fd(m_SSL.get(), socket->GetFD());
83 if (m_Role == RoleServer)
84 SSL_set_accept_state(m_SSL.get());
86 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
87 if (!hostname.IsEmpty())
88 SSL_set_tlsext_host_name(m_SSL.get(), hostname.CStr());
89 #endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
91 SSL_set_connect_state(m_SSL.get());
95 TlsStream::~TlsStream()
100 int TlsStream::ValidateCertificate(int preverify_ok, X509_STORE_CTX *ctx)
102 auto *ssl = static_cast<SSL *>(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
103 auto *stream = static_cast<TlsStream *>(SSL_get_ex_data(ssl, m_SSLIndex));
106 stream->m_VerifyOK = false;
108 std::ostringstream msgbuf;
109 int err = X509_STORE_CTX_get_error(ctx);
110 msgbuf << "code " << err << ": " << X509_verify_cert_error_string(err);
111 stream->m_VerifyError = msgbuf.str();
117 bool TlsStream::IsVerifyOK() const
122 String TlsStream::GetVerifyError() const
124 return m_VerifyError;
128 * Retrieves the X509 certficate for this client.
130 * @returns The X509 certificate.
132 std::shared_ptr<X509> TlsStream::GetClientCertificate() const
134 boost::mutex::scoped_lock lock(m_Mutex);
135 return std::shared_ptr<X509>(SSL_get_certificate(m_SSL.get()), &Utility::NullDeleter);
139 * Retrieves the X509 certficate for the peer.
141 * @returns The X509 certificate.
143 std::shared_ptr<X509> TlsStream::GetPeerCertificate() const
145 boost::mutex::scoped_lock lock(m_Mutex);
146 return std::shared_ptr<X509>(SSL_get_peer_certificate(m_SSL.get()), X509_free);
149 void TlsStream::OnEvent(int revents)
154 boost::mutex::scoped_lock lock(m_Mutex);
159 char buffer[64 * 1024];
161 if (m_CurrentAction == TlsActionNone) {
162 if (revents & (POLLIN | POLLERR | POLLHUP))
163 m_CurrentAction = TlsActionRead;
164 else if (m_SendQ->GetAvailableBytes() > 0 && (revents & POLLOUT))
165 m_CurrentAction = TlsActionWrite;
167 ChangeEvents(POLLIN);
173 bool success = false;
175 /* Clear error queue for this thread before using SSL_{read,write,do_handshake}.
176 * Otherwise SSL_*_error() does not work reliably.
180 size_t readTotal = 0;
182 switch (m_CurrentAction) {
185 rc = SSL_read(m_SSL.get(), buffer, sizeof(buffer));
188 m_RecvQ->Write(buffer, rc);
194 #ifdef I2_DEBUG /* I2_DEBUG */
195 Log(LogDebug, "TlsStream")
196 << "Read bytes: " << rc << " Total read bytes: " << readTotal;
197 #endif /* I2_DEBUG */
198 /* Limit read size. We cannot do this check inside the while loop
199 * since below should solely check whether OpenSSL has more data
201 if (readTotal >= 64 * 1024) {
202 #ifdef I2_DEBUG /* I2_DEBUG */
203 Log(LogWarning, "TlsStream")
204 << "Maximum read bytes exceeded: " << readTotal;
205 #endif /* I2_DEBUG */
209 /* Use OpenSSL's state machine here to determine whether we need
210 * to read more data. SSL_has_pending() is available with 1.1.0.
212 } while (SSL_pending(m_SSL.get()));
219 count = m_SendQ->Peek(buffer, sizeof(buffer), true);
221 rc = SSL_write(m_SSL.get(), buffer, count);
224 m_SendQ->Read(nullptr, rc, true);
229 case TlsActionHandshake:
230 rc = SSL_do_handshake(m_SSL.get());
234 m_HandshakeOK = true;
240 VERIFY(!"Invalid TlsAction");
244 int err = SSL_get_error(m_SSL.get(), rc);
247 case SSL_ERROR_WANT_READ:
249 ChangeEvents(POLLIN);
252 case SSL_ERROR_WANT_WRITE:
254 ChangeEvents(POLLOUT);
257 case SSL_ERROR_ZERO_RETURN:
264 m_ErrorCode = ERR_peek_error();
265 m_ErrorOccurred = true;
267 if (m_ErrorCode != 0) {
268 Log(LogWarning, "TlsStream")
269 << "OpenSSL error: " << ERR_error_string(m_ErrorCode, nullptr);
271 Log(LogWarning, "TlsStream", "TLS stream was disconnected.");
283 m_CurrentAction = TlsActionNone;
286 if (m_SendQ->GetAvailableBytes() > 0)
287 ChangeEvents(POLLIN|POLLOUT);
289 ChangeEvents(POLLIN);
294 while (m_RecvQ->IsDataAvailable() && IsHandlingEvents())
295 SignalDataAvailable();
298 if (m_Shutdown && !m_SendQ->IsDataAvailable()) {
306 void TlsStream::HandleError() const
308 if (m_ErrorOccurred) {
309 BOOST_THROW_EXCEPTION(openssl_error()
310 << boost::errinfo_api_function("TlsStream::OnEvent")
311 << errinfo_openssl_error(m_ErrorCode));
315 void TlsStream::Handshake()
317 boost::mutex::scoped_lock lock(m_Mutex);
319 m_CurrentAction = TlsActionHandshake;
320 ChangeEvents(POLLOUT);
322 boost::system_time const timeout = boost::get_system_time() + boost::posix_time::milliseconds(long(Configuration::TlsHandshakeTimeout * 1000));
324 while (!m_HandshakeOK && !m_ErrorOccurred && !m_Eof && timeout > boost::get_system_time())
325 m_CV.timed_wait(lock, timeout);
327 if (timeout < boost::get_system_time())
328 BOOST_THROW_EXCEPTION(std::runtime_error("Timeout was reached (" + Convert::ToString(Configuration::TlsHandshakeTimeout) + ") during TLS handshake."));
331 BOOST_THROW_EXCEPTION(std::runtime_error("Socket was closed during TLS handshake."));
337 * Processes data for the stream.
339 size_t TlsStream::Peek(void *buffer, size_t count, bool allow_partial)
341 boost::mutex::scoped_lock lock(m_Mutex);
344 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
349 return m_RecvQ->Peek(buffer, count, true);
352 size_t TlsStream::Read(void *buffer, size_t count, bool allow_partial)
354 boost::mutex::scoped_lock lock(m_Mutex);
357 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
362 return m_RecvQ->Read(buffer, count, true);
365 void TlsStream::Write(const void *buffer, size_t count)
367 boost::mutex::scoped_lock lock(m_Mutex);
369 m_SendQ->Write(buffer, count);
371 ChangeEvents(POLLIN|POLLOUT);
374 void TlsStream::Shutdown()
377 ChangeEvents(POLLOUT);
383 void TlsStream::Close()
385 CloseInternal(false);
388 void TlsStream::CloseInternal(bool inDestructor)
396 SignalDataAvailable();
398 SocketEvents::Unregister();
402 boost::mutex::scoped_lock lock(m_Mutex);
407 /* https://www.openssl.org/docs/manmaster/man3/SSL_shutdown.html
409 * It is recommended to do a bidirectional shutdown by checking
410 * the return value of SSL_shutdown() and call it again until
411 * it returns 1 or a fatal error. A maximum of 2x pending + 2x data
416 for (int i = 0; i < 4; i++) {
417 if ((rc = SSL_shutdown(m_SSL.get())))
429 bool TlsStream::IsEof() const
431 return m_Eof && m_RecvQ->GetAvailableBytes() < 1u;
434 bool TlsStream::SupportsWaiting() const
439 bool TlsStream::IsDataAvailable() const
441 boost::mutex::scoped_lock lock(m_Mutex);
443 return m_RecvQ->GetAvailableBytes() > 0;
446 Socket::Ptr TlsStream::GetSocket() const