1 /******************************************************************************
3 * Copyright (C) 2012-2018 Icinga Development Team (https://www.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"
30 #define TLS_TIMEOUT_SECONDS 10
32 using namespace icinga;
34 int TlsStream::m_SSLIndex;
35 bool TlsStream::m_SSLIndexInitialized = false;
38 * Constructor for the TlsStream class.
40 * @param role The role of the client.
41 * @param sslContext The SSL context for the client.
43 TlsStream::TlsStream(const Socket::Ptr& socket, const String& hostname, ConnectionRole role, const std::shared_ptr<SSL_CTX>& sslContext)
44 : SocketEvents(socket, this), m_Eof(false), m_HandshakeOK(false), m_VerifyOK(true), m_ErrorCode(0),
45 m_ErrorOccurred(false), m_Socket(socket), m_Role(role), m_SendQ(new FIFO()), m_RecvQ(new FIFO()),
46 m_CurrentAction(TlsActionNone), m_Retry(false), m_Shutdown(false)
48 std::ostringstream msgbuf;
51 m_SSL = std::shared_ptr<SSL>(SSL_new(sslContext.get()), SSL_free);
54 msgbuf << "SSL_new() failed with code " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
55 Log(LogCritical, "TlsStream", msgbuf.str());
57 BOOST_THROW_EXCEPTION(openssl_error()
58 << boost::errinfo_api_function("SSL_new")
59 << errinfo_openssl_error(ERR_peek_error()));
62 if (!m_SSLIndexInitialized) {
63 m_SSLIndex = SSL_get_ex_new_index(0, const_cast<char *>("TlsStream"), nullptr, nullptr, nullptr);
64 m_SSLIndexInitialized = true;
67 SSL_set_ex_data(m_SSL.get(), m_SSLIndex, this);
69 SSL_set_verify(m_SSL.get(), SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, &TlsStream::ValidateCertificate);
71 socket->MakeNonBlocking();
73 SSL_set_fd(m_SSL.get(), socket->GetFD());
75 if (m_Role == RoleServer)
76 SSL_set_accept_state(m_SSL.get());
78 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
79 if (!hostname.IsEmpty())
80 SSL_set_tlsext_host_name(m_SSL.get(), hostname.CStr());
81 #endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
83 SSL_set_connect_state(m_SSL.get());
87 TlsStream::~TlsStream()
92 int TlsStream::ValidateCertificate(int preverify_ok, X509_STORE_CTX *ctx)
94 auto *ssl = static_cast<SSL *>(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
95 auto *stream = static_cast<TlsStream *>(SSL_get_ex_data(ssl, m_SSLIndex));
98 stream->m_VerifyOK = false;
100 std::ostringstream msgbuf;
101 int err = X509_STORE_CTX_get_error(ctx);
102 msgbuf << "code " << err << ": " << X509_verify_cert_error_string(err);
103 stream->m_VerifyError = msgbuf.str();
109 bool TlsStream::IsVerifyOK() const
114 String TlsStream::GetVerifyError() const
116 return m_VerifyError;
120 * Retrieves the X509 certficate for this client.
122 * @returns The X509 certificate.
124 std::shared_ptr<X509> TlsStream::GetClientCertificate() const
126 boost::mutex::scoped_lock lock(m_Mutex);
127 return std::shared_ptr<X509>(SSL_get_certificate(m_SSL.get()), &Utility::NullDeleter);
131 * Retrieves the X509 certficate for the peer.
133 * @returns The X509 certificate.
135 std::shared_ptr<X509> TlsStream::GetPeerCertificate() const
137 boost::mutex::scoped_lock lock(m_Mutex);
138 return std::shared_ptr<X509>(SSL_get_peer_certificate(m_SSL.get()), X509_free);
141 void TlsStream::OnEvent(int revents)
146 boost::mutex::scoped_lock lock(m_Mutex);
151 char buffer[64 * 1024];
153 if (m_CurrentAction == TlsActionNone) {
154 bool corked = IsCorked();
155 if (!corked && (revents & (POLLIN | POLLERR | POLLHUP)))
156 m_CurrentAction = TlsActionRead;
157 else if (m_SendQ->GetAvailableBytes() > 0 && (revents & POLLOUT))
158 m_CurrentAction = TlsActionWrite;
163 ChangeEvents(POLLIN);
169 bool success = false;
171 /* Clear error queue for this thread before using SSL_{read,write,do_handshake}.
172 * Otherwise SSL_*_error() does not work reliably.
176 size_t readTotal = 0;
178 switch (m_CurrentAction) {
181 rc = SSL_read(m_SSL.get(), buffer, sizeof(buffer));
184 m_RecvQ->Write(buffer, rc);
189 } while (rc > 0 && readTotal < 64 * 1024);
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 (!IsCorked() && 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::seconds(TLS_TIMEOUT_SECONDS);
301 while (!m_HandshakeOK && !m_ErrorOccurred && !m_Eof && timeout > boost::get_system_time())
302 m_CV.timed_wait(lock, timeout);
304 // We should _NOT_ (underline, bold, itallic and wordart) throw an exception for a timeout.
305 if (timeout < boost::get_system_time())
306 BOOST_THROW_EXCEPTION(std::runtime_error("Timeout during handshake."));
309 BOOST_THROW_EXCEPTION(std::runtime_error("Socket was closed during TLS handshake."));
315 * Processes data for the stream.
317 size_t TlsStream::Peek(void *buffer, size_t count, bool allow_partial)
319 boost::mutex::scoped_lock lock(m_Mutex);
322 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
327 return m_RecvQ->Peek(buffer, count, true);
330 size_t TlsStream::Read(void *buffer, size_t count, bool allow_partial)
332 boost::mutex::scoped_lock lock(m_Mutex);
335 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
340 return m_RecvQ->Read(buffer, count, true);
343 void TlsStream::Write(const void *buffer, size_t count)
345 boost::mutex::scoped_lock lock(m_Mutex);
347 m_SendQ->Write(buffer, count);
349 ChangeEvents(POLLIN|POLLOUT);
352 void TlsStream::Shutdown()
355 ChangeEvents(POLLOUT);
361 void TlsStream::Close()
363 CloseInternal(false);
366 void TlsStream::CloseInternal(bool inDestructor)
374 SignalDataAvailable();
376 SocketEvents::Unregister();
380 boost::mutex::scoped_lock lock(m_Mutex);
385 (void)SSL_shutdown(m_SSL.get());
394 bool TlsStream::IsEof() const
399 bool TlsStream::SupportsWaiting() const
404 bool TlsStream::IsDataAvailable() const
406 boost::mutex::scoped_lock lock(m_Mutex);
408 return m_RecvQ->GetAvailableBytes() > 0;
411 void TlsStream::SetCorked(bool corked)
413 Stream::SetCorked(corked);
415 boost::mutex::scoped_lock lock(m_Mutex);
418 m_CurrentAction = TlsActionNone;
420 ChangeEvents(POLLIN | POLLOUT);
423 Socket::Ptr TlsStream::GetSocket() const