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, this), 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 bool corked = IsCorked();
157 if (!corked && (revents & (POLLIN | POLLERR | POLLHUP)))
158 m_CurrentAction = TlsActionRead;
159 else if (m_SendQ->GetAvailableBytes() > 0 && (revents & POLLOUT))
160 m_CurrentAction = TlsActionWrite;
165 ChangeEvents(POLLIN);
171 bool success = false;
173 /* Clear error queue for this thread before using SSL_{read,write,do_handshake}.
174 * Otherwise SSL_*_error() does not work reliably.
178 size_t readTotal = 0;
180 switch (m_CurrentAction) {
183 rc = SSL_read(m_SSL.get(), buffer, sizeof(buffer));
186 m_RecvQ->Write(buffer, rc);
192 #ifdef I2_DEBUG /* I2_DEBUG */
193 Log(LogDebug, "TlsStream")
194 << "Read bytes: " << rc << " Total read bytes: " << readTotal;
195 #endif /* I2_DEBUG */
196 /* Limit read size. We cannot do this check inside the while loop
197 * since below should solely check whether OpenSSL has more data
199 if (readTotal >= 64 * 1024) {
200 #ifdef I2_DEBUG /* I2_DEBUG */
201 Log(LogWarning, "TlsStream")
202 << "Maximum read bytes exceeded: " << readTotal;
203 #endif /* I2_DEBUG */
207 /* Use OpenSSL's state machine here to determine whether we need
208 * to read more data. SSL_has_pending() is available with 1.1.0.
210 } while (SSL_pending(m_SSL.get()));
217 count = m_SendQ->Peek(buffer, sizeof(buffer), true);
219 rc = SSL_write(m_SSL.get(), buffer, count);
222 m_SendQ->Read(nullptr, rc, true);
227 case TlsActionHandshake:
228 rc = SSL_do_handshake(m_SSL.get());
232 m_HandshakeOK = true;
238 VERIFY(!"Invalid TlsAction");
242 int err = SSL_get_error(m_SSL.get(), rc);
245 case SSL_ERROR_WANT_READ:
247 ChangeEvents(POLLIN);
250 case SSL_ERROR_WANT_WRITE:
252 ChangeEvents(POLLOUT);
255 case SSL_ERROR_ZERO_RETURN:
262 m_ErrorCode = ERR_peek_error();
263 m_ErrorOccurred = true;
265 if (m_ErrorCode != 0) {
266 Log(LogWarning, "TlsStream")
267 << "OpenSSL error: " << ERR_error_string(m_ErrorCode, nullptr);
269 Log(LogWarning, "TlsStream", "TLS stream was disconnected.");
281 m_CurrentAction = TlsActionNone;
284 if (m_SendQ->GetAvailableBytes() > 0)
285 ChangeEvents(POLLIN|POLLOUT);
287 ChangeEvents(POLLIN);
292 while (!IsCorked() && m_RecvQ->IsDataAvailable() && IsHandlingEvents())
293 SignalDataAvailable();
296 if (m_Shutdown && !m_SendQ->IsDataAvailable()) {
304 void TlsStream::HandleError() const
306 if (m_ErrorOccurred) {
307 BOOST_THROW_EXCEPTION(openssl_error()
308 << boost::errinfo_api_function("TlsStream::OnEvent")
309 << errinfo_openssl_error(m_ErrorCode));
313 void TlsStream::Handshake()
315 boost::mutex::scoped_lock lock(m_Mutex);
317 m_CurrentAction = TlsActionHandshake;
318 ChangeEvents(POLLOUT);
320 boost::system_time const timeout = boost::get_system_time() + boost::posix_time::milliseconds(long(Configuration::TlsHandshakeTimeout * 1000));
322 while (!m_HandshakeOK && !m_ErrorOccurred && !m_Eof && timeout > boost::get_system_time())
323 m_CV.timed_wait(lock, timeout);
325 if (timeout < boost::get_system_time())
326 BOOST_THROW_EXCEPTION(std::runtime_error("Timeout was reached (" + Convert::ToString(Configuration::TlsHandshakeTimeout) + ") during TLS handshake."));
329 BOOST_THROW_EXCEPTION(std::runtime_error("Socket was closed during TLS handshake."));
335 * Processes data for the stream.
337 size_t TlsStream::Peek(void *buffer, size_t count, bool allow_partial)
339 boost::mutex::scoped_lock lock(m_Mutex);
342 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
347 return m_RecvQ->Peek(buffer, count, true);
350 size_t TlsStream::Read(void *buffer, size_t count, bool allow_partial)
352 boost::mutex::scoped_lock lock(m_Mutex);
355 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
360 return m_RecvQ->Read(buffer, count, true);
363 void TlsStream::Write(const void *buffer, size_t count)
365 boost::mutex::scoped_lock lock(m_Mutex);
367 m_SendQ->Write(buffer, count);
369 ChangeEvents(POLLIN|POLLOUT);
372 void TlsStream::Shutdown()
375 ChangeEvents(POLLOUT);
381 void TlsStream::Close()
383 CloseInternal(false);
386 void TlsStream::CloseInternal(bool inDestructor)
394 SignalDataAvailable();
396 SocketEvents::Unregister();
400 boost::mutex::scoped_lock lock(m_Mutex);
405 /* https://www.openssl.org/docs/manmaster/man3/SSL_shutdown.html
407 * It is recommended to do a bidirectional shutdown by checking
408 * the return value of SSL_shutdown() and call it again until
409 * it returns 1 or a fatal error. A maximum of 2x pending + 2x data
414 for (int i = 0; i < 4; i++) {
415 if ((rc = SSL_shutdown(m_SSL.get())))
427 bool TlsStream::IsEof() const
429 return m_Eof && m_RecvQ->GetAvailableBytes() < 1u;
432 bool TlsStream::SupportsWaiting() const
437 bool TlsStream::IsDataAvailable() const
439 boost::mutex::scoped_lock lock(m_Mutex);
441 return m_RecvQ->GetAvailableBytes() > 0;
444 void TlsStream::SetCorked(bool corked)
446 Stream::SetCorked(corked);
448 boost::mutex::scoped_lock lock(m_Mutex);
451 m_CurrentAction = TlsActionNone;
453 ChangeEvents(POLLIN | POLLOUT);
456 Socket::Ptr TlsStream::GetSocket() const