1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
3 #include "base/application.hpp"
4 #include "base/tlsstream.hpp"
5 #include "base/utility.hpp"
6 #include "base/exception.hpp"
7 #include "base/logger.hpp"
8 #include "base/configuration.hpp"
9 #include "base/convert.hpp"
10 #include <boost/asio/ssl/context.hpp>
11 #include <boost/asio/ssl/verify_context.hpp>
12 #include <boost/asio/ssl/verify_mode.hpp>
14 #include <openssl/ssl.h>
15 #include <openssl/tls1.h>
16 #include <openssl/x509.h>
23 #define TLS_TIMEOUT_SECONDS 10
25 using namespace icinga;
27 int TlsStream::m_SSLIndex;
28 bool TlsStream::m_SSLIndexInitialized = false;
31 * Constructor for the TlsStream class.
33 * @param role The role of the client.
34 * @param sslContext The SSL context for the client.
36 TlsStream::TlsStream(const Socket::Ptr& socket, const String& hostname, ConnectionRole role, const std::shared_ptr<SSL_CTX>& sslContext)
37 : TlsStream(socket, hostname, role, sslContext.get())
42 * Constructor for the TlsStream class.
44 * @param role The role of the client.
45 * @param sslContext The SSL context for the client.
47 TlsStream::TlsStream(const Socket::Ptr& socket, const String& hostname, ConnectionRole role, const std::shared_ptr<boost::asio::ssl::context>& sslContext)
48 : TlsStream(socket, hostname, role, sslContext->native_handle())
53 * Constructor for the TlsStream class.
55 * @param role The role of the client.
56 * @param sslContext The SSL context for the client.
58 TlsStream::TlsStream(const Socket::Ptr& socket, const String& hostname, ConnectionRole role, SSL_CTX* sslContext)
59 : SocketEvents(socket), m_Eof(false), m_HandshakeOK(false), m_VerifyOK(true), m_ErrorCode(0),
60 m_ErrorOccurred(false), m_Socket(socket), m_Role(role), m_SendQ(new FIFO()), m_RecvQ(new FIFO()),
61 m_CurrentAction(TlsActionNone), m_Retry(false), m_Shutdown(false)
63 std::ostringstream msgbuf;
66 m_SSL = std::shared_ptr<SSL>(SSL_new(sslContext), SSL_free);
69 msgbuf << "SSL_new() failed with code " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
70 Log(LogCritical, "TlsStream", msgbuf.str());
72 BOOST_THROW_EXCEPTION(openssl_error()
73 << boost::errinfo_api_function("SSL_new")
74 << errinfo_openssl_error(ERR_peek_error()));
77 if (!m_SSLIndexInitialized) {
78 m_SSLIndex = SSL_get_ex_new_index(0, const_cast<char *>("TlsStream"), nullptr, nullptr, nullptr);
79 m_SSLIndexInitialized = true;
82 SSL_set_ex_data(m_SSL.get(), m_SSLIndex, this);
84 SSL_set_verify(m_SSL.get(), SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, &TlsStream::ValidateCertificate);
86 socket->MakeNonBlocking();
88 SSL_set_fd(m_SSL.get(), socket->GetFD());
90 if (m_Role == RoleServer)
91 SSL_set_accept_state(m_SSL.get());
93 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
94 if (!hostname.IsEmpty())
95 SSL_set_tlsext_host_name(m_SSL.get(), hostname.CStr());
96 #endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
98 SSL_set_connect_state(m_SSL.get());
102 TlsStream::~TlsStream()
107 int TlsStream::ValidateCertificate(int preverify_ok, X509_STORE_CTX *ctx)
109 auto *ssl = static_cast<SSL *>(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
110 auto *stream = static_cast<TlsStream *>(SSL_get_ex_data(ssl, m_SSLIndex));
113 stream->m_VerifyOK = false;
115 std::ostringstream msgbuf;
116 int err = X509_STORE_CTX_get_error(ctx);
117 msgbuf << "code " << err << ": " << X509_verify_cert_error_string(err);
118 stream->m_VerifyError = msgbuf.str();
124 bool TlsStream::IsVerifyOK() const
129 String TlsStream::GetVerifyError() const
131 return m_VerifyError;
135 * Retrieves the X509 certficate for this client.
137 * @returns The X509 certificate.
139 std::shared_ptr<X509> TlsStream::GetClientCertificate() const
141 boost::mutex::scoped_lock lock(m_Mutex);
142 return std::shared_ptr<X509>(SSL_get_certificate(m_SSL.get()), &Utility::NullDeleter);
146 * Retrieves the X509 certficate for the peer.
148 * @returns The X509 certificate.
150 std::shared_ptr<X509> TlsStream::GetPeerCertificate() const
152 boost::mutex::scoped_lock lock(m_Mutex);
153 return std::shared_ptr<X509>(SSL_get_peer_certificate(m_SSL.get()), X509_free);
156 void TlsStream::OnEvent(int revents)
161 boost::mutex::scoped_lock lock(m_Mutex);
166 char buffer[64 * 1024];
168 if (m_CurrentAction == TlsActionNone) {
169 if (revents & (POLLIN | POLLERR | POLLHUP))
170 m_CurrentAction = TlsActionRead;
171 else if (m_SendQ->GetAvailableBytes() > 0 && (revents & POLLOUT))
172 m_CurrentAction = TlsActionWrite;
174 ChangeEvents(POLLIN);
180 bool success = false;
182 /* Clear error queue for this thread before using SSL_{read,write,do_handshake}.
183 * Otherwise SSL_*_error() does not work reliably.
187 size_t readTotal = 0;
189 switch (m_CurrentAction) {
192 rc = SSL_read(m_SSL.get(), buffer, sizeof(buffer));
195 m_RecvQ->Write(buffer, rc);
201 #ifdef I2_DEBUG /* I2_DEBUG */
202 Log(LogDebug, "TlsStream")
203 << "Read bytes: " << rc << " Total read bytes: " << readTotal;
204 #endif /* I2_DEBUG */
205 /* Limit read size. We cannot do this check inside the while loop
206 * since below should solely check whether OpenSSL has more data
208 if (readTotal >= 64 * 1024) {
209 #ifdef I2_DEBUG /* I2_DEBUG */
210 Log(LogWarning, "TlsStream")
211 << "Maximum read bytes exceeded: " << readTotal;
212 #endif /* I2_DEBUG */
216 /* Use OpenSSL's state machine here to determine whether we need
217 * to read more data. SSL_has_pending() is available with 1.1.0.
219 } while (SSL_pending(m_SSL.get()));
226 count = m_SendQ->Peek(buffer, sizeof(buffer), true);
228 rc = SSL_write(m_SSL.get(), buffer, count);
231 m_SendQ->Read(nullptr, rc, true);
236 case TlsActionHandshake:
237 rc = SSL_do_handshake(m_SSL.get());
241 m_HandshakeOK = true;
247 VERIFY(!"Invalid TlsAction");
251 int err = SSL_get_error(m_SSL.get(), rc);
254 case SSL_ERROR_WANT_READ:
256 ChangeEvents(POLLIN);
259 case SSL_ERROR_WANT_WRITE:
261 ChangeEvents(POLLOUT);
264 case SSL_ERROR_ZERO_RETURN:
271 m_ErrorCode = ERR_peek_error();
272 m_ErrorOccurred = true;
274 if (m_ErrorCode != 0) {
276 Log(LogWarning, "TlsStream")
277 << "OpenSSL error: " << ERR_error_string(m_ErrorCode, errbuf);
279 Log(LogWarning, "TlsStream", "TLS stream was disconnected.");
291 m_CurrentAction = TlsActionNone;
294 if (m_SendQ->GetAvailableBytes() > 0)
295 ChangeEvents(POLLIN|POLLOUT);
297 ChangeEvents(POLLIN);
302 while (m_RecvQ->IsDataAvailable() && IsHandlingEvents())
303 SignalDataAvailable();
306 if (m_Shutdown && !m_SendQ->IsDataAvailable()) {
314 void TlsStream::HandleError() const
316 if (m_ErrorOccurred) {
317 BOOST_THROW_EXCEPTION(openssl_error()
318 << boost::errinfo_api_function("TlsStream::OnEvent")
319 << errinfo_openssl_error(m_ErrorCode));
323 void TlsStream::Handshake()
325 boost::mutex::scoped_lock lock(m_Mutex);
327 m_CurrentAction = TlsActionHandshake;
328 ChangeEvents(POLLOUT);
330 boost::system_time const timeout = boost::get_system_time() + boost::posix_time::milliseconds(long(Configuration::TlsHandshakeTimeout * 1000));
332 while (!m_HandshakeOK && !m_ErrorOccurred && !m_Eof && timeout > boost::get_system_time())
333 m_CV.timed_wait(lock, timeout);
335 if (timeout < boost::get_system_time())
336 BOOST_THROW_EXCEPTION(std::runtime_error("Timeout was reached (" + Convert::ToString(Configuration::TlsHandshakeTimeout) + ") during TLS handshake."));
339 BOOST_THROW_EXCEPTION(std::runtime_error("Socket was closed during TLS handshake."));
345 * Processes data for the stream.
347 size_t TlsStream::Peek(void *buffer, size_t count, bool allow_partial)
349 boost::mutex::scoped_lock lock(m_Mutex);
352 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
357 return m_RecvQ->Peek(buffer, count, true);
360 size_t TlsStream::Read(void *buffer, size_t count, bool allow_partial)
362 boost::mutex::scoped_lock lock(m_Mutex);
365 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
370 return m_RecvQ->Read(buffer, count, true);
373 void TlsStream::Write(const void *buffer, size_t count)
375 boost::mutex::scoped_lock lock(m_Mutex);
377 m_SendQ->Write(buffer, count);
379 ChangeEvents(POLLIN|POLLOUT);
382 void TlsStream::Shutdown()
385 ChangeEvents(POLLOUT);
391 void TlsStream::Close()
393 CloseInternal(false);
396 void TlsStream::CloseInternal(bool inDestructor)
404 SignalDataAvailable();
406 SocketEvents::Unregister();
410 boost::mutex::scoped_lock lock(m_Mutex);
415 /* https://www.openssl.org/docs/manmaster/man3/SSL_shutdown.html
417 * It is recommended to do a bidirectional shutdown by checking
418 * the return value of SSL_shutdown() and call it again until
419 * it returns 1 or a fatal error. A maximum of 2x pending + 2x data
424 for (int i = 0; i < 4; i++) {
425 if ((rc = SSL_shutdown(m_SSL.get())))
437 bool TlsStream::IsEof() const
439 return m_Eof && m_RecvQ->GetAvailableBytes() < 1u;
442 bool TlsStream::SupportsWaiting() const
447 bool TlsStream::IsDataAvailable() const
449 boost::mutex::scoped_lock lock(m_Mutex);
451 return m_RecvQ->GetAvailableBytes() > 0;
454 Socket::Ptr TlsStream::GetSocket() const
459 bool UnbufferedAsioTlsStream::IsVerifyOK() const
464 String UnbufferedAsioTlsStream::GetVerifyError() const
466 return m_VerifyError;
469 std::shared_ptr<X509> UnbufferedAsioTlsStream::GetPeerCertificate()
471 return std::shared_ptr<X509>(SSL_get_peer_certificate(native_handle()), X509_free);
474 void UnbufferedAsioTlsStream::BeforeHandshake(handshake_type type)
476 namespace ssl = boost::asio::ssl;
478 set_verify_mode(ssl::verify_peer | ssl::verify_client_once);
480 set_verify_callback([this](bool preverified, ssl::verify_context& ctx) {
484 std::ostringstream msgbuf;
485 int err = X509_STORE_CTX_get_error(ctx.native_handle());
487 msgbuf << "code " << err << ": " << X509_verify_cert_error_string(err);
488 m_VerifyError = msgbuf.str();
494 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
495 if (type == client && !m_Hostname.IsEmpty()) {
496 String environmentName = Application::GetAppEnvironment();
497 String serverName = m_Hostname;
499 if (!environmentName.IsEmpty())
500 serverName += ":" + environmentName;
502 SSL_set_tlsext_host_name(native_handle(), serverName.CStr());
504 #endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */