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"
15 #define TLS_TIMEOUT_SECONDS 10
17 using namespace icinga;
19 int TlsStream::m_SSLIndex;
20 bool TlsStream::m_SSLIndexInitialized = false;
23 * Constructor for the TlsStream class.
25 * @param role The role of the client.
26 * @param sslContext The SSL context for the client.
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)
33 std::ostringstream msgbuf;
36 m_SSL = std::shared_ptr<SSL>(SSL_new(sslContext.get()), SSL_free);
39 msgbuf << "SSL_new() failed with code " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
40 Log(LogCritical, "TlsStream", msgbuf.str());
42 BOOST_THROW_EXCEPTION(openssl_error()
43 << boost::errinfo_api_function("SSL_new")
44 << errinfo_openssl_error(ERR_peek_error()));
47 if (!m_SSLIndexInitialized) {
48 m_SSLIndex = SSL_get_ex_new_index(0, const_cast<char *>("TlsStream"), nullptr, nullptr, nullptr);
49 m_SSLIndexInitialized = true;
52 SSL_set_ex_data(m_SSL.get(), m_SSLIndex, this);
54 SSL_set_verify(m_SSL.get(), SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, &TlsStream::ValidateCertificate);
56 socket->MakeNonBlocking();
58 SSL_set_fd(m_SSL.get(), socket->GetFD());
60 if (m_Role == RoleServer)
61 SSL_set_accept_state(m_SSL.get());
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 */
68 SSL_set_connect_state(m_SSL.get());
72 TlsStream::~TlsStream()
77 int TlsStream::ValidateCertificate(int preverify_ok, X509_STORE_CTX *ctx)
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));
83 stream->m_VerifyOK = false;
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();
94 bool TlsStream::IsVerifyOK() const
99 String TlsStream::GetVerifyError() const
101 return m_VerifyError;
105 * Retrieves the X509 certficate for this client.
107 * @returns The X509 certificate.
109 std::shared_ptr<X509> TlsStream::GetClientCertificate() const
111 boost::mutex::scoped_lock lock(m_Mutex);
112 return std::shared_ptr<X509>(SSL_get_certificate(m_SSL.get()), &Utility::NullDeleter);
116 * Retrieves the X509 certficate for the peer.
118 * @returns The X509 certificate.
120 std::shared_ptr<X509> TlsStream::GetPeerCertificate() const
122 boost::mutex::scoped_lock lock(m_Mutex);
123 return std::shared_ptr<X509>(SSL_get_peer_certificate(m_SSL.get()), X509_free);
126 void TlsStream::OnEvent(int revents)
131 boost::mutex::scoped_lock lock(m_Mutex);
136 char buffer[64 * 1024];
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;
144 ChangeEvents(POLLIN);
150 bool success = false;
152 /* Clear error queue for this thread before using SSL_{read,write,do_handshake}.
153 * Otherwise SSL_*_error() does not work reliably.
157 size_t readTotal = 0;
159 switch (m_CurrentAction) {
162 rc = SSL_read(m_SSL.get(), buffer, sizeof(buffer));
165 m_RecvQ->Write(buffer, rc);
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
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 */
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.
189 } while (SSL_pending(m_SSL.get()));
196 count = m_SendQ->Peek(buffer, sizeof(buffer), true);
198 rc = SSL_write(m_SSL.get(), buffer, count);
201 m_SendQ->Read(nullptr, rc, true);
206 case TlsActionHandshake:
207 rc = SSL_do_handshake(m_SSL.get());
211 m_HandshakeOK = true;
217 VERIFY(!"Invalid TlsAction");
221 int err = SSL_get_error(m_SSL.get(), rc);
224 case SSL_ERROR_WANT_READ:
226 ChangeEvents(POLLIN);
229 case SSL_ERROR_WANT_WRITE:
231 ChangeEvents(POLLOUT);
234 case SSL_ERROR_ZERO_RETURN:
241 m_ErrorCode = ERR_peek_error();
242 m_ErrorOccurred = true;
244 if (m_ErrorCode != 0) {
245 Log(LogWarning, "TlsStream")
246 << "OpenSSL error: " << ERR_error_string(m_ErrorCode, nullptr);
248 Log(LogWarning, "TlsStream", "TLS stream was disconnected.");
260 m_CurrentAction = TlsActionNone;
263 if (m_SendQ->GetAvailableBytes() > 0)
264 ChangeEvents(POLLIN|POLLOUT);
266 ChangeEvents(POLLIN);
271 while (m_RecvQ->IsDataAvailable() && IsHandlingEvents())
272 SignalDataAvailable();
275 if (m_Shutdown && !m_SendQ->IsDataAvailable()) {
283 void TlsStream::HandleError() const
285 if (m_ErrorOccurred) {
286 BOOST_THROW_EXCEPTION(openssl_error()
287 << boost::errinfo_api_function("TlsStream::OnEvent")
288 << errinfo_openssl_error(m_ErrorCode));
292 void TlsStream::Handshake()
294 boost::mutex::scoped_lock lock(m_Mutex);
296 m_CurrentAction = TlsActionHandshake;
297 ChangeEvents(POLLOUT);
299 boost::system_time const timeout = boost::get_system_time() + boost::posix_time::milliseconds(long(Configuration::TlsHandshakeTimeout * 1000));
301 while (!m_HandshakeOK && !m_ErrorOccurred && !m_Eof && timeout > boost::get_system_time())
302 m_CV.timed_wait(lock, timeout);
304 if (timeout < boost::get_system_time())
305 BOOST_THROW_EXCEPTION(std::runtime_error("Timeout was reached (" + Convert::ToString(Configuration::TlsHandshakeTimeout) + ") during TLS handshake."));
308 BOOST_THROW_EXCEPTION(std::runtime_error("Socket was closed during TLS handshake."));
314 * Processes data for the stream.
316 size_t TlsStream::Peek(void *buffer, size_t count, bool allow_partial)
318 boost::mutex::scoped_lock lock(m_Mutex);
321 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
326 return m_RecvQ->Peek(buffer, count, true);
329 size_t TlsStream::Read(void *buffer, size_t count, bool allow_partial)
331 boost::mutex::scoped_lock lock(m_Mutex);
334 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
339 return m_RecvQ->Read(buffer, count, true);
342 void TlsStream::Write(const void *buffer, size_t count)
344 boost::mutex::scoped_lock lock(m_Mutex);
346 m_SendQ->Write(buffer, count);
348 ChangeEvents(POLLIN|POLLOUT);
351 void TlsStream::Shutdown()
354 ChangeEvents(POLLOUT);
360 void TlsStream::Close()
362 CloseInternal(false);
365 void TlsStream::CloseInternal(bool inDestructor)
373 SignalDataAvailable();
375 SocketEvents::Unregister();
379 boost::mutex::scoped_lock lock(m_Mutex);
384 /* https://www.openssl.org/docs/manmaster/man3/SSL_shutdown.html
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
393 for (int i = 0; i < 4; i++) {
394 if ((rc = SSL_shutdown(m_SSL.get())))
406 bool TlsStream::IsEof() const
408 return m_Eof && m_RecvQ->GetAvailableBytes() < 1u;
411 bool TlsStream::SupportsWaiting() const
416 bool TlsStream::IsDataAvailable() const
418 boost::mutex::scoped_lock lock(m_Mutex);
420 return m_RecvQ->GetAvailableBytes() > 0;
423 Socket::Ptr TlsStream::GetSocket() const