1 /******************************************************************************
3 * Copyright (C) 2012-2018 Icinga Development Team (https://icinga.com/) *
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. *
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. *
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 ******************************************************************************/
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"
32 #define TLS_TIMEOUT_SECONDS 10
34 using namespace icinga;
36 int TlsStream::m_SSLIndex;
37 bool TlsStream::m_SSLIndexInitialized = false;
40 * Constructor for the TlsStream class.
42 * @param role The role of the client.
43 * @param sslContext The SSL context for the client.
45 TlsStream::TlsStream(const Socket::Ptr& socket, const String& hostname, ConnectionRole role, const std::shared_ptr<SSL_CTX>& sslContext)
46 : SocketEvents(socket), 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)
50 std::ostringstream msgbuf;
53 m_SSL = std::shared_ptr<SSL>(SSL_new(sslContext.get()), SSL_free);
56 msgbuf << "SSL_new() failed with code " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
57 Log(LogCritical, "TlsStream", msgbuf.str());
59 BOOST_THROW_EXCEPTION(openssl_error()
60 << boost::errinfo_api_function("SSL_new")
61 << errinfo_openssl_error(ERR_peek_error()));
64 if (!m_SSLIndexInitialized) {
65 m_SSLIndex = SSL_get_ex_new_index(0, const_cast<char *>("TlsStream"), nullptr, nullptr, nullptr);
66 m_SSLIndexInitialized = true;
69 SSL_set_ex_data(m_SSL.get(), m_SSLIndex, this);
71 SSL_set_verify(m_SSL.get(), SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, &TlsStream::ValidateCertificate);
73 socket->MakeNonBlocking();
75 SSL_set_fd(m_SSL.get(), socket->GetFD());
77 if (m_Role == RoleServer)
78 SSL_set_accept_state(m_SSL.get());
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 */
85 SSL_set_connect_state(m_SSL.get());
89 TlsStream::~TlsStream()
94 int TlsStream::ValidateCertificate(int preverify_ok, X509_STORE_CTX *ctx)
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));
100 stream->m_VerifyOK = false;
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();
111 bool TlsStream::IsVerifyOK() const
116 String TlsStream::GetVerifyError() const
118 return m_VerifyError;
122 * Retrieves the X509 certficate for this client.
124 * @returns The X509 certificate.
126 std::shared_ptr<X509> TlsStream::GetClientCertificate() const
128 boost::mutex::scoped_lock lock(m_Mutex);
129 return std::shared_ptr<X509>(SSL_get_certificate(m_SSL.get()), &Utility::NullDeleter);
133 * Retrieves the X509 certficate for the peer.
135 * @returns The X509 certificate.
137 std::shared_ptr<X509> TlsStream::GetPeerCertificate() const
139 boost::mutex::scoped_lock lock(m_Mutex);
140 return std::shared_ptr<X509>(SSL_get_peer_certificate(m_SSL.get()), X509_free);
143 void TlsStream::OnEvent(int revents)
148 boost::mutex::scoped_lock lock(m_Mutex);
153 char buffer[64 * 1024];
155 if (m_CurrentAction == TlsActionNone) {
156 if (revents & (POLLIN | POLLERR | POLLHUP))
157 m_CurrentAction = TlsActionRead;
158 else if (m_SendQ->GetAvailableBytes() > 0 && (revents & POLLOUT))
159 m_CurrentAction = TlsActionWrite;
161 ChangeEvents(POLLIN);
167 bool success = false;
169 /* Clear error queue for this thread before using SSL_{read,write,do_handshake}.
170 * Otherwise SSL_*_error() does not work reliably.
174 size_t readTotal = 0;
176 switch (m_CurrentAction) {
179 rc = SSL_read(m_SSL.get(), buffer, sizeof(buffer));
182 m_RecvQ->Write(buffer, rc);
188 #ifdef I2_DEBUG /* I2_DEBUG */
189 Log(LogDebug, "TlsStream")
190 << "Read bytes: " << rc << " Total read bytes: " << readTotal;
191 #endif /* I2_DEBUG */
192 /* Limit read size. We cannot do this check inside the while loop
193 * since below should solely check whether OpenSSL has more data
195 if (readTotal >= 64 * 1024) {
196 #ifdef I2_DEBUG /* I2_DEBUG */
197 Log(LogWarning, "TlsStream")
198 << "Maximum read bytes exceeded: " << readTotal;
199 #endif /* I2_DEBUG */
203 /* Use OpenSSL's state machine here to determine whether we need
204 * to read more data. SSL_has_pending() is available with 1.1.0.
206 } while (SSL_pending(m_SSL.get()));
213 count = m_SendQ->Peek(buffer, sizeof(buffer), true);
215 rc = SSL_write(m_SSL.get(), buffer, count);
218 m_SendQ->Read(nullptr, rc, true);
223 case TlsActionHandshake:
224 rc = SSL_do_handshake(m_SSL.get());
228 m_HandshakeOK = true;
234 VERIFY(!"Invalid TlsAction");
238 int err = SSL_get_error(m_SSL.get(), rc);
241 case SSL_ERROR_WANT_READ:
243 ChangeEvents(POLLIN);
246 case SSL_ERROR_WANT_WRITE:
248 ChangeEvents(POLLOUT);
251 case SSL_ERROR_ZERO_RETURN:
258 m_ErrorCode = ERR_peek_error();
259 m_ErrorOccurred = true;
261 if (m_ErrorCode != 0) {
262 Log(LogWarning, "TlsStream")
263 << "OpenSSL error: " << ERR_error_string(m_ErrorCode, nullptr);
265 Log(LogWarning, "TlsStream", "TLS stream was disconnected.");
277 m_CurrentAction = TlsActionNone;
280 if (m_SendQ->GetAvailableBytes() > 0)
281 ChangeEvents(POLLIN|POLLOUT);
283 ChangeEvents(POLLIN);
288 while (m_RecvQ->IsDataAvailable() && IsHandlingEvents())
289 SignalDataAvailable();
292 if (m_Shutdown && !m_SendQ->IsDataAvailable()) {
300 void TlsStream::HandleError() const
302 if (m_ErrorOccurred) {
303 BOOST_THROW_EXCEPTION(openssl_error()
304 << boost::errinfo_api_function("TlsStream::OnEvent")
305 << errinfo_openssl_error(m_ErrorCode));
309 void TlsStream::Handshake()
311 boost::mutex::scoped_lock lock(m_Mutex);
313 m_CurrentAction = TlsActionHandshake;
314 ChangeEvents(POLLOUT);
316 boost::system_time const timeout = boost::get_system_time() + boost::posix_time::milliseconds(long(Configuration::TlsHandshakeTimeout * 1000));
318 while (!m_HandshakeOK && !m_ErrorOccurred && !m_Eof && timeout > boost::get_system_time())
319 m_CV.timed_wait(lock, timeout);
321 if (timeout < boost::get_system_time())
322 BOOST_THROW_EXCEPTION(std::runtime_error("Timeout was reached (" + Convert::ToString(Configuration::TlsHandshakeTimeout) + ") during TLS handshake."));
325 BOOST_THROW_EXCEPTION(std::runtime_error("Socket was closed during TLS handshake."));
331 * Processes data for the stream.
333 size_t TlsStream::Peek(void *buffer, size_t count, bool allow_partial)
335 boost::mutex::scoped_lock lock(m_Mutex);
338 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
343 return m_RecvQ->Peek(buffer, count, true);
346 size_t TlsStream::Read(void *buffer, size_t count, bool allow_partial)
348 boost::mutex::scoped_lock lock(m_Mutex);
351 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
356 return m_RecvQ->Read(buffer, count, true);
359 void TlsStream::Write(const void *buffer, size_t count)
361 boost::mutex::scoped_lock lock(m_Mutex);
363 m_SendQ->Write(buffer, count);
365 ChangeEvents(POLLIN|POLLOUT);
368 void TlsStream::Shutdown()
371 ChangeEvents(POLLOUT);
377 void TlsStream::Close()
379 CloseInternal(false);
382 void TlsStream::CloseInternal(bool inDestructor)
390 SignalDataAvailable();
392 SocketEvents::Unregister();
396 boost::mutex::scoped_lock lock(m_Mutex);
401 /* https://www.openssl.org/docs/manmaster/man3/SSL_shutdown.html
403 * It is recommended to do a bidirectional shutdown by checking
404 * the return value of SSL_shutdown() and call it again until
405 * it returns 1 or a fatal error. A maximum of 2x pending + 2x data
410 for (int i = 0; i < 4; i++) {
411 if ((rc = SSL_shutdown(m_SSL.get())))
423 bool TlsStream::IsEof() const
425 return m_Eof && m_RecvQ->GetAvailableBytes() < 1u;
428 bool TlsStream::SupportsWaiting() const
433 bool TlsStream::IsDataAvailable() const
435 boost::mutex::scoped_lock lock(m_Mutex);
437 return m_RecvQ->GetAvailableBytes() > 0;
440 Socket::Ptr TlsStream::GetSocket() const